jason
jason

Reputation: 4801

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.

Upvotes: 6

Views: 2896

Answers (4)

Tess Rosania
Tess Rosania

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

Tadeck
Tadeck

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

Upvotes: 3

Owen
Owen

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

Alexander Gessler
Alexander Gessler

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

Related Questions