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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With