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].
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.
Let's take this one step at a time:
i.difference(x)
doesn't modify i
or x
. Rather, it returns a new set. i = i.difference(x)
rebinds the variable i
to point to the new set. It does not affect the contents of the list in any way. a[idx] = i
does modify the list by setting its idx
-th element to the new set. A cleaner implementation might use a different variable instead of re-purposing i
:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
diff=i.difference(x)
# a[idx]=diff
print a
Yes, when you execute i=i.difference(x)
it creates a new i
. Just modify your code like this to understand what is happening -
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?
print 'old i - ', id(i)
i=i.difference(x)
print 'new i - ', id(i)
print a
test()
Output -
old i - 4467059736
new i - 4467179216
old i - 4467177360
new i - 4467179216
[set([1, 2, 3]), set([3, 4, 5])]
Your use of set.difference() suggests that you don't know the operator -=
for sets:
def test():
a=[set([1,2,3]),set([3,4,5])]
x=set([1,4])
for i in a:
i -= x
print a
This shows that i
is just another pointer to the set you want to modify. Just don't overwrite your pointer!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.