Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lists in python, with references [duplicate]

How do I copy the contents of a list and not just a reference to the list in Python?

like image 782
Lizard Avatar asked Nov 27 '25 16:11

Lizard


2 Answers

Look at the copy module, and notice the difference between shallow and deep copies:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

like image 165
gimel Avatar answered Nov 29 '25 04:11

gimel


Use a slice notation.

newlist = oldlist

This will assign a second name to the same list

newlist = oldlist[:]

This will duplicate each element of oldlist into a complete new list called newlist

like image 39
Lizard Avatar answered Nov 29 '25 04:11

Lizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!