Sometimes, we want to choose longest string in list with Python.
In this article, we’ll look at how to choose longest string in list with Python.
How to choose longest string in list with Python?
To choose longest string in list with Python, we can use the max
function with the key
parameter set to len
.
For instance, we write:
l = ['123', '123456', '1234']
m = max(l, key=len)
print(m)
We call max
on list l
with key
set to len
compare each entry in l
by their lengths.
Therefore, the longest string will be returned.
And m
is '123456'
.
Conclusion
To choose longest string in list with Python, we can use the max
function with the key
parameter set to len
.