What is the difference between these two python functions

Today I had an interview, and I had a question that I answered incorrectly. Here's the question:

def gen():
    return [lambda x: x + i for i in range(4)]

print([m(1) for m in gen()])

The result is [4, 4, 4, 4]. My answer was [1, 2, 3, 4]. I also executed the following code.

def gen():
    return (lambda x: x + i for i in range(4))

print([m(1) for m in gen()])

The result is [1, 2, 3, 4]. Can anyone explain? I'm so confused.

+4
source share
2 answers

The second piece of code that uses ()is a generator. Used to save memory

Take a look at PEP-289

0
source

Using parentheses, you set all the numbers to the last number generated.

PS im not a python guy, but it should be something like this :)

-1
source

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


All Articles