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
  • 500
  • 6
  • 21
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. – xoxel 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

1 Answers1

0

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

Look at PEP-289

AB Abhi
  • 2,476
  • 22
  • 30