0

Find max length of name

Find max length of the name names=['abcdg','hdksuoh','ar']

17th Sep 2021, 7:04 AM
Amol Bhandekar
Amol Bhandekar - avatar
7 Respostas
+ 2
Amol Bhandekar If you use the max function on the names list with len as the key, as in my 1st post, it will return the longest name in the list, not the length of that name. You can then just use the len() function on the name to get the length of that longest name if you also want it. longest_name = max(names, key=len) len_of_longest _name = len(longest_name) If you want to loop through the names and get both the longest name and its length at the same time; longest = ('', 0) for name in names: if len(name) > longest[1]: longest = name, len(name) print(*longest)
17th Sep 2021, 7:28 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
there are two ways : 1.using loop 2. max(names, key=len)
17th Sep 2021, 7:13 AM
Pariket Thakur
Pariket Thakur - avatar
+ 1
Try; max(names, key=len)
17th Sep 2021, 7:09 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Let me correct I have tried like this new_list=[] for i in names: new_list.append(len(i)) print(max(new_list)) How to print the names belongs the list?
17th Sep 2021, 7:18 AM
Amol Bhandekar
Amol Bhandekar - avatar
+ 1
Hey Thanks man :)
17th Sep 2021, 7:44 AM
Amol Bhandekar
Amol Bhandekar - avatar
0
Thanks, Chaotic Dawg I know about max function is there any other way?
17th Sep 2021, 7:10 AM
Amol Bhandekar
Amol Bhandekar - avatar
0
You could loop through the elements of the list and check the length of each, saving the longest. p.s. this is basically what the max() function will do anyhow, given the len function as the key function to use.
17th Sep 2021, 7:12 AM
ChaoticDawg
ChaoticDawg - avatar