Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 965
Sid Avatar asked Mar 21 '12 15:03

Sid


People also ask

Can I modify list while iterating?

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.

How to create a list in a loop in Python?

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.

Can we iterate list in Python?

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.

Is appending to a list Slow?

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.


1 Answers

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.

iteration

i = i.difference(x) creates new object and assigns i to it.

assignment

like image 65
Steven T. Snyder Avatar answered Sep 23 '22 06:09

Steven T. Snyder