Python Forum

Full Version: why the generator expression after IF always returns True
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Why is the generator expression after IF statement always return True? Is it because the if statement only checks whether there is a new value "generated" by the expression, if so, then it will return True? But the below expression (a>100 for in x) will not generate a new value, will it?

For example:

x=[1,2,3,4,5]
y=[a**2 for a in x if (a>100 for a in x)]
print(y)
The result is
[1, 4, 9, 16, 25]
Thanks in advance!
from the docs
Quote:In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
https://docs.python.org/3/reference/expressions.html
generator is an object, not empty container.
also question on SO
https://stackoverflow.com/questions/7976...-exhausted

all that said, your code does not make lot of sense. what do you want to achieve?