Reputation: 1991
Why do the two statements below result in a different outcome? What am I missing here?
list = [1,2]
if (item < 0 for item in list):
print "This prints."
for item in list:
if item < 0:
print "This doesn't print."
Upvotes: 0
Views: 31
Reputation: 3782
Your first if is a generator expression. It will always be True because it is not None
:
alist = [1,2]
if (item < 0 for item in alist):
print 'always be True'
print (item < 0 for item in alist)
print (item < 0 for item in alist).next()
print [i for i in (item < 0 for item in alist)]
Your second code is ok for the logic.
Note: do not use list as a variable name.
Upvotes: 0
Reputation: 117981
The first is a generator expression, and the truthiness will be determined by whether or not any items are produced. It will either print exactly once or zero times. In this sense, you would get the same behavior for any length list.
The second actually iterates over each item, and will print for each item that satisfies that condition.
A (hacky) workaround to make this a one-liner would be
>>> l = [-1, -2, 1, 2]
>>> print('this prints\n' * len([item for item in l if item < 0]))
this prints
this prints
Upvotes: 5