Reputation: 4801
print max(3 for i in range(4))
#output is 3
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea what the 3 means in this context...] max() returns the biggest iterable passed to it and the result is printed to screen.
Upvotes: 6
Views: 2896
Reputation: 10103
This evaluates to:
print max([3,3,3,3])
... which is an elaborate way to say print 3
.
expr for x in xs
is a generator expression. Typically, you would use x
in expr
. For example:
[2*i for i in range(4)] #=> [0, 2, 4, 6]
Upvotes: 11
Reputation: 137440
The expression:
print max(3 for i in range(4))
is printing the result of the max()
function, applied to what is inside the parentheses. Inside the parentheses however, you have a generator expression creating something similar to an array, with all elements equal to 3
, but in a more efficient way than the expression:
print max([3 for i in range(4)])
which will create an array of 3
s and destroy it after it is no longer needed.
Basically: because inside the parentheses you will create only values that are equal, and the max()
function returns the biggest one, you do not need to create more than one element. Because with the number of elements always equal to one, the max()
function becomes not needed and your code can be effectively replaced (at least in the case you have given) by the following code:
print 3
That is simply all ;)
To read more about differences between comprehension and generator expression, you can visit this documentation page.
Upvotes: 3
Reputation: 1561
It can be rewritten as:
nums = []
for i in range(4):
nums.append(3)
print max(nums) # 3! Hurrah!
I hope that makes its pointlessness more obvious.
Upvotes: 7
Reputation: 46657
3 for i in range(4)
is a generator that yields 3 four times in a row and max
takes an iterable and returns the element with the highest value, which is, obviously, three here.
Upvotes: 14