-3

how to check from a python string list which is the largest item and copy it to another list. i was trying this. but i dosnt Works.

cad_1 = ['hello', 'hello', 'ewe', 'uwu']
cad_final = {i,j for i,j in Cad_1 if len(i)>=len(j)}
print(cad_final);          
4
  • This will produce a NameError before even getting to the second line... the second line is a set comprehension and you can't loop through a list like that anyway. If you want help you need to clarify exactly what the error is. Commented Nov 6, 2018 at 7:49
  • @PanBasic you want all longest strings (both "hello"s) or only one? Commented Nov 6, 2018 at 7:50
  • Welcome to StackOverflow! Are hello, ewe, and uwu variables or string? Can you clarify what do you mean by largest? Largest value? Longest string? By alphabetical order? Commented Nov 6, 2018 at 7:50
  • Specify "doesn't work". What is your expected output, and what is your actual output? As it stands, this code doesn't run. Commented Nov 6, 2018 at 7:51

1 Answer 1

0

You can first create a dictionary with the respective string length:

my_length_list = {i:len(i) for i in my_list}

and then get the largest element by

import operator

max_string_len = max(my_length_list.items(), key=operator.itemgetter(1))[0]

and write this value in another list

max_string_list = [max_string_len]
Sign up to request clarification or add additional context in comments.

3 Comments

or max(my_list, key=len).
this is simples one!
Ah thank you, I did not know this :) Fairly simply like this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.