Q:

Temporary created during python list iteration?

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]. 

A:

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.

A:

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

