I was playing around with a block of code during which I stumbled upon some unexpected behaviour of Python.
I defined a list as follows:
a = [1, 2, 3]
Made another list with a loop:
res = (item for item in a if a.count(item) > 0)
print(list(res)) # [1, 2, 3] -- as expected -- Consider this is line 1
Then later I changed the initial value of first list:
a = [7, 2, 9]
I was expecting no change in res
as the changes I made to a
were after res
was created, but to my surprise, the value of res was changed.
print(list(res)) # prints [] -- Consider this as line 2
What's more shocking is that the result of print depends on print statement on line 1, if I comment out print statement at line1 then line 2 prints [2]
Can someone please explain me what's going on here?