1

I have a function like this:

def main2():
    props = []
    prop_list = []
    i=0
    while (i < 10):
        new_prop = {
            'i': 1
        }
        props.append(new_prop)
        prop_list.append({'i': 1, 'props': props,})
        if i == 0:
            print prop_list
        i += 1
    print prop_list[0]

It outputs this:

[{'i': 1, 'props': [{'i': 1}]}]
{'i': 1, 'props': [{'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}, {'i': 1}]}

Why is the final print not the same as the first print? The previously added elements in the list appear to be updating when I append a new element.

2 Answers 2

2

With this line,

prop_list.append({'i': 1, 'props': props,})

the dict includes the props list object. This list is mutated on subsequent iterations through the loop:

props.append(new_prop)

The final value printed for prop_list[0] reflects this change.


Here is the same thing in isolation:

In [23]: x = []

In [24]: y = {'foo': x}

In [25]: y
Out[25]: {'foo': []}

In [26]: z = {'baz': x}

In [27]: x.append('bar')    # x is mutated

In [28]: y                 
Out[28]: {'foo': ['bar']}   # both y and z are affected

In [29]: z
Out[29]: {'baz': ['bar']}

If you do not want this to happen, make a copy of the list. To make a shallow copy of props, use props[:]:

prop_list.append({'i': 1, 'props': props[:]})

Note that the shallow copy, props[:] is a new list containing the exact same items as props. That means if props contained a mutable item such as a list, mutating that list would affect both props and its shallow copy.

To make a deep copy of all the items in props (recursively), use

import copy
prop_list.append({'i': 1, 'props': copy.deepcopy(props)})
4
  • The props list object will change, but why would prop_list.append update prop_list[0]? shouldn't it just add prop_list[1], etc?
    – N. Taggart
    May 7, 2013 at 21:17
  • 1
    In Python variable names such as props "point" at objects. Each time through the loop, the variable name props is pointing to the very same object -- no copies of the object. Mutating that object affects all the places where that object exists.
    – unutbu
    May 7, 2013 at 21:20
  • 1
    @N.Taggart prop_list[0] holds a reference to the props object, so when that changes, it reflects in prop_list[0]. May 7, 2013 at 21:21
  • Ok, that makes sense. Since it's referencing the object and the object is changing... I get it. Thanks!
    – N. Taggart
    May 7, 2013 at 21:21
1

In the line

prop_list.append({'i': 1, 'props': props,})

the props always refers to the same object, initialised at the top

props = []

and appended to in each iteration of the while loop.

2
  • yes, the props object will iterate, but why would it update earlier list elements in prop_list? in this case, should prop_list[0] be equal to prop_list[1]?
    – N. Taggart
    May 7, 2013 at 21:19
  • 1
    It should indeed. All elements of prop_list are equal. May 7, 2013 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.