Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find length of an element in a list?

Tags:

python

list

I'm just starting with programming. I have a list of a few strings and now I need to print the biggest (in length) one. So I first want to just print the lengths of elements. I was trying things like this:

l = ("xxxxxxxxx", "yyyy","zz")

for i in range(len(l)):

So how do I do it?

like image 671
S7nf Avatar asked Oct 27 '09 09:10

S7nf


People also ask

How do you find the length of an element in a list?

Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

Can you use LEN () on a list?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.

How do I get the length of a list of elements in Python?

Python has a built-in function len() for getting the total number of items in a list, tuple, arrays, dictionary etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.

Which method is used to find the length of a list?

The len() method offers the most used and easy way to find the length of any list. This is the most conventional technique adopted by all programmers today.


1 Answers

l = ("xxxxxxxxx", "yyyy","zz")
print(max(l, key=len))

First of all you don't have a list, you have a tuple. this code will work for any sequence, however; both lists and tuples are sequences (as well as strings, sets, etc). So, the max function takes a key argument, that is used to sort the elements of an iterable. So, from all elements of l will be selected the one having the maximum length.

like image 167
SilentGhost Avatar answered Sep 18 '22 13:09

SilentGhost