I'm running a list comprehension of a list of numbers as strings so for example the list looks like this
vals = ['0.13', '324', '0.23432']
and try a list comprehension like this:
best = [x for x in vals > 0.02]
and I get a TypeError: iteration over non-sequence.
Isn't a list a sequence that should be the first thing you should be able to iterate through? What is a sequence?
It's hard to find answers to basic questions I'm finding.
Thanks.
You need to check if each item is greater than '0.02', not whether the sequence is greater.
Your original expression,
[x for x in vals > '0.02']is parsed as[x for x in (vals > '0.02')]. Sincevals > '0.02'is a boolean value, and not a sequence, it's not possible to iterate over it.EDIT: I updated this answer to use the string
'0.02'per Joe's suggestion in the comments (thank you). That works in this scenario, but in the event that you really wanted to do a numeric comparison instead of a lexicographic one, you could use:This converts
xto a float so that you are comparing a floating-point number to another floating-point number, probably as intended. The result of the list comprehension will still be a list of strings, since we are collecting[x for ...]and not[float(x) for ...]. Just some food for thought.