简体   繁体   中英

Python: identical items in list are treated as the same

I have a nested list in python. Each item the second list is also a nested list. My goal is to duplicate one list, insert it right at the same index, and then modify each one. So, example of start condition:

 myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me]]]

Duplication/insertion at myList[1][2]:

 myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me], [duplicate_me]]]

This all works fine. However, when I run the append code:

 myList[1][2].append(new_element)

It appends the new element to both duplicates, like this:

 myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me, new_element], [duplicate_me, new_element]]]

Is there something bizarre going on in the way the elements are called or indexed? I see a potential workaround (calling the item to be duplicated to a working variable, modifying it there, and then inserting it at the same point), but that seems needlessly complex.

Thanks!

myList[1][2] and myList[1][3] don't just have the same values, they are actually the same list. You are looking at the same area in memory when you read both of them. So, when you change one, you are changing the other, because both are actually the exact same thing! Instead doing what you do to duplicate the list, you should make a copy of it.

Here's an example of the problem from a python shell:

>>> mylist = [1, 2, 3]
>>> newlist = mylist
>>> newlist.append(4)
>>> newlist
[1, 2, 3, 4]
>>> mylist
[1, 2, 3, 4]

A common way to fix this is to use one of these tricks:

>>> mylist = [1, 2, 3]
>>> newlist = mylist[:]  # OR :
>>> newlist = [x for x in mylist]
>>> newlist.append(4)
>>> newlist
[1, 2, 3, 4]
>>> mylist
[1, 2, 3]

The second and third lines will create a copy of the list. I tend to combine the two like this, if I need to copy a 2D list:

>>> newlist = [x[:] for x in mylist]

Use one of these to create your duplicate, and all will be well again.

You are most likely not duplicating the target list (*[duplicate_me]*), but rather simply appending a duplicated reference to the same list into myList .

You need to copy the list before adding it to myList. One simple way is to call the list constructor passing in the original [duplicate_me]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM