Strange python for syntax, how does it work, what did he call?

print max(3 for i in range(4)) #output is 3 

Using Python 2.6

3 throws me away, I'm trying to explain what is happening.

for i in the range (4) makes a loop that loops 4 times, increasing i from 0 to 3 at the beginning of each cycle. [I don't know what 3 means in this context ...] max () returns the largest iterable passed to it, and the result is printed onto the screen.

+6
source share
4 answers

3 for i in range(4) is a generator that gives 3 four times in a row, and max takes iterability and returns the element with the highest value, which is obviously three here.

+14
source

This is rated as:

 print max([3,3,3,3]) 

... which is a tricky way to say print 3 .

expr for x in xs is a generator expression. Typically, you use x in expr . For instance:

[2*i for i in range(4)] #=> [0, 2, 4, 6]

+9
source

It can be rewritten as:

 nums = [] for i in range(4): nums.append(3) print max(nums) # 3! Hurrah! 

I hope this makes its meaninglessness more apparent.

+5
source

Expression:

 print max(3 for i in range(4)) 

Prints the result of the max() function applied to what is in parentheses. However, in brackets you have an expression expression that creates 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 array 3 and destroy it after it is no longer needed.

Basically, since you create only equal values ​​in brackets, and the max() function returns the largest, you do not need to create multiple elements. Since the number of elements is always equal to one, the max() function becomes unnecessary, and your code can be effectively replaced (at least if you gave) with the following code:

 print 3 

That's just it;)

To learn more about the differences between an understanding expression and a generator expression, visit this page.

+2
source

Source: https://habr.com/ru/post/888073/


All Articles