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

4

6
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.

Pasia answered 13/5, 2011 at 20:41 Comment(1)
For some reason this question reminds me of Monty Python and the Holy Grail.Grillage
B
14

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.

Bartolomeo answered 13/5, 2011 at 20:43 Comment(0)
N
11

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]
Neologism answered 13/5, 2011 at 20:43 Comment(4)
so, the 3 there means 'do this for loop 3 times'? Seems a very odd thing, gonna have to experiment.Pasia
Nah, the 3 there is what's being added to the list every time the loop goes round. So for the first number in range(4), which is 0, add the number 3... then for the next number, add the number three, and the next, and the next. So you end up with a list of four threes.Improvisator
ahhhh so 'heres 3, treat it as an i'Pasia
Careful: actually this evaluates to: print max(iter([3,3,3,3])) Given that it's a generator expression rather than a list comprehension.Ventriloquism
I
7

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.

Improvisator answered 13/5, 2011 at 20:44 Comment(0)
A
3

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 3s 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.

Advocate answered 13/5, 2011 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.