Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change an element in a list, and keep a copy of the original list?

Tags:

python

I've searched around and tried a lot of stuff but I can't get this to work. I think the problem is something to do with how Python list names point to the list, rather than being the actual list, but I still can't figure it out. The situation is this (it's a list of dictionaries):

list_original = [dictionary1, dictionary2, dictionary3]
dictionary2_modified = dictionarymodifier(dictionary2) #some function that modifies the chosen element
list_modified = [i for i in list_original] #makes copy of original list
for i,n in enumerate(dictionary_original):
    if i==1:
        list_modified[1] = dictionary2_modified #replaces element with modified version
return list_original, list_modified

And many similar things, but I always either get two of the original list or two of the new list! I add that I'm using python 2.4 and don't have a choice in that.

Many thanks for any help

like image 549
user2023030 Avatar asked Dec 01 '25 04:12

user2023030


1 Answers

Mutable vs. Immutable

You need to know the difference between mutable and immutable elements. Namely, both dictionaries and lists in Python are mutable. Which means that if you modify it in one place, it is also modified in the other place.

In addition, the variable of mutable type (like list or dict) can contain immutable elements (eg. str), as well as the other way around: variable of immutable type (eg. tuple) can contain mutable elements (such as list or dict).

Example for mutability

So, this shows the mutability using the example of list:

>>> a = [1, 2, 3, 4]
>>> b = a
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> a[2] = 'x'
>>> a
[1, 2, 'x', 4]
>>> b
[1, 2, 'x', 4]

How to obtain a copy of list or dict

To obtain a copy of list, you simply can do this instead:

new_list = old_list[:]  # the slicing at the end just takes the whole list

In case of dict this is generally sufficient:

new_dict = old_dict.copy()

Nested lists / dicts

However, although lists / dicts that are flat or contain only mutable elements, can be copied the way I showed, to obtain a copy of more complex mutable data structures you need to do something more...

In such case very helpful may be the copy module with its deepcopy function. Documentation of copy module says more about its purpose:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

like image 132
Tadeck Avatar answered Dec 02 '25 18:12

Tadeck