I was trying to use a generator to save on some memory and ran into a problem. I am a bit surprised at the result because my understanding was that integers were immutable, so can someone explain what's going on?
>>>> a = []
>>>> for i in range(10):
.... a.append((i for _ in [0]))
....
>>>> list(a[0])
[9]
When I do it using list comprehension instead it does what I want:
>>>> a = []
>>>> for i in range(10):
.... a.append([i for _ in [0]])
....
>>>> a
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
I can sort of reason that what's going on is that the generator is somehow getting a "reference" to the value of i
, which, after the last time through the loop is 9, but this seems anti-pythonic as python doesn't have references as such (at least as far as I understand).
Questions:
- What is going on? How is this possible? A link to some python docs that can explain exactly what's going on would be appreciated.
- How can I do what I want (use a generator with a variable that's going to change in the future but which I need the current value for something)?
Update:
Realistic use case:
def get_some_iter(a, b):
iters = []
for i in a:
m = do_something(i, len(b))
iters.append((SomeObj(j, m) for j in itertools.combinations(b, i))
return itertools.chain(*iters)