4

today I had an interview and got a question that I answered wrong. 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 ran 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]. Could anyone explain? I am so confused.

Purple Haze
  • 530
  • 7
  • 22
Aaron.Z
  • 41
  • 3
  • 1
    The first one has [ ] brackets and the second (). Using [ ] all the numbers are always set to the last value added. – Nathan Apr 03 '18 at 15:32
  • @Nathan i was curious about the answer, could you make one with more details ? Also upvoted, found that interesting. – N.K Apr 03 '18 at 15:34
  • 1
    Good question and with good answer https://stackoverflow.com/questions/28268439/python-list-comprehension-with-lambdas – BENY Apr 03 '18 at 15:35
  • Using `[]`, all the lambdas are created immediately, but when they are evaluated in the second list comprehension, the `i` from the first list comprehension (which is closed over) is equal to `3` - this is all as explained in the linked duplicates. Using `()`, the lambdas are created on demand when the `print` line's list comprehension runs, so each `lambda` is getting created immediately before being called, with the corresponding `i` value. – Karl Knechtel Aug 18 '22 at 05:51

1 Answers1

0

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

Look at PEP-289

Abhishake Gupta
  • 2,939
  • 1
  • 25
  • 34