I want to understand why the following is happening. My guess is that a temporary is being created during list iteration, but want some experts to confirm this:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
# doesn't actually modify list contents, making a copy of list elements in i?
i=i.difference(x)
print a
for idx,i in enumerate(a):
i=i.difference(x)
print id(i),id(a[idx])
# obviously this modifies the contents
a[idx]=i
print a
Output:
[set([1, 2, 3]), set([3, 4, 5])]
59672976 59672616
59672616 59672736
[set([2, 3]), set([3, 5])]
Also, I want to understand why the "id" of i in the second iteration is the same as the "id" for a[0].
The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
Using for Loops You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list.
Solution: If you append to the list using a sub routine the process slows and slows as the list grows. This does not happen if you do it inline. Even calling garbage collection makes no difference.
It helps to look at this graphically, because it's basically a pointer problem.
for i in a
iteratively assigns i
to each element in a
.
i = i.difference(x)
creates and assigns i
to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With