Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange python for syntax, how does this work, whats it called?

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.

like image 383
jason Avatar asked May 13 '11 20:05

jason


3 Answers

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.

like image 58
Alexander Gessler Avatar answered Oct 18 '22 10:10

Alexander Gessler


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]
like image 40
Paul Rosania Avatar answered Oct 18 '22 11:10

Paul Rosania


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.

like image 7
Owen Avatar answered Oct 18 '22 11:10

Owen