I want to duplicate a list and modify the duplicate, but when I try this, I end up modifying the original as well.
A highly simplified version of my problem:
list = [2,3,6,8,9,6,7,4,56,8,9,6,7,8]
new_list = list
new_list[2] = 'n'
print list
print new_list
I only want to change item 2 of the new list, but when I try this, both the new list and the old list change to:
[2,3,'n',8,9,6,7,4,56,8,9,6,7,8]
Is there something quite fundamental I’m missing here?
I can make it do what I want if I add each item of the list to the next list one by one:
list = [2,3,6,8,9,6,7,4,56,8,9,6,7,8]
new_list = []
for item in list:
new_list.append(item)
new_list[2] = 'n'
print list
print new_list
If I do that, only the new_list changes, but is there a more straight-forward way?
To make a new copy of your list, try:
Or more
crypticconcise via slicing:Just assigning
oldListtonewListwill result in two names pointing to the same object, like so:Generic object copying functions are provided by the copy module. (Image taken from: http://henry.precheur.org/python/copy_list).