1

This code prints 2 2 2 instead of 1 2 3. I'd understand this result if k being referred to is shared between each list items, but I couldn't be certain about it.

flist = [(lambda x: k) for k in range(3)]
print(flist[0](0), flist[1](0), flist[2](0))
print(k)  # Fails as expected
  1. How does list comprehension work exactly? On what namespace does k exist?
  2. How should I change the code to get 1 2 3 with about the same code complexities/length as list comprehension? I'm hardcoding list of flists, and I don't want my code to be excessively long.
Cœur
  • 37,241
  • 25
  • 195
  • 267
whyask37
  • 123
  • 8

1 Answers1

0

this is simple it should be like this:

>>> flist = [ k+1 for k in range(3)]
>>> flist
[1, 2, 3]
Hackaholic
  • 19,069
  • 5
  • 54
  • 72