Is there a way to store the results of a loop into a Sequence variable in Python

Question:

I have a list of names

names = ["David","Olivia","Charlotte"] 

I want to measure the length of each name in this list and store the integer value in a list like L=[] and using the max function to determine which name is the longest. Something like below:

L = []
for x in names:
   L = len(x)
print(max(L))

but I get this error in the terminal that the defined L variable is not iterable. How do I store the results in L variable as a sequence?

Asked By: IX SOBEK XI

||

Answers:

append to the list, don’t overwrite it.

L: list[int] = []
for x in names:
   L.append(len(x))
print(max(L))

Actually, it’s more efficient to create the list “on the fly”:

L: list[int] = [len(x) for x in names]
print(max(L))

… or not to create a list at all:

print(max(len(x) for x in names))
Answered By: StSav012

This is a great use for a (list) comprehension:

names = ["David", "Olivia", "Charlotte"]
lengths = (len(name) for name in names)
print(max(lengths))

Above just uses a generator comprehension, but if you used brackets instead of parens you’d create a list:

lengths = [len(name) for name in names]

The generator is somewhat faster because you only move over the list once. max() lets you shorthand the generator:

print(max(len(name) for name in names))

max() also lets you do this:

max(names, key=len)

In this case, the key parameter is taking a function that returns a value that can be used to determine the maximum value. This returns the value of the longest item:

>>> names = ["David", "Olivia", "Charlotte"]
>>> max(names, key=len)
'Charlotte'

Alternatively, if you want to use reduce (a functional style approach), you can do this:

>>> from functools import reduce
>>> reduce( lambda x, y: max(x, len(y)), names, 0)
9

This moves through the list and compares a starting value (0) with the length of each new value (len(y)), and chooses one at each step. This is basically equivalent, but can be a useful alternative in more nuanced circumstances.

Answered By: Nathaniel Ford

If you just care about the longest name, there’s no need to create a list at all:

max_length = 0
names = ["David","Olivia","Charlotte"]
for name in names:
    max_length = max(max_length, len(name))

Note that in this case, you can initialize max_length to 0 because no name can have less than 0 characters in it. In a more general case where you are dealing with quantities that might be negative, you can use max_length=float('-inf'), which obviously also works for this problem.

Answered By: Kraigolas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.