Home  >  Article  >  Backend Development  >  How to clone a list in python

How to clone a list in python

silencement
silencementOriginal
2019-05-25 09:22:073216browse

How to clone a list in python

#How to copy a list in Python?

Some people may say, isn't this a very simple thing? Wouldn't it be better to just have new_list = old_list?
Is this actually feasible? Let's give an example:

How to clone a list in python

Don't you think it's amazing? When my original list changes, my newly copied list also changes. Not the result I want. So, why does this happen?
It turns out that when using assignment (=) in Python, it actually just points to a reference to the new variable. To put it simply, when we execute a=b, the actual operation is to assign the memory address of a. Given b, a and b point to the same memory address at this time. It does not open a new memory address for b, so whenever the value in the memory address changes, the value of b will also change accordingly.

So how should we copy it correctly? If the list contains immutable data, the following methods can be used:

How to clone a list in python

We can randomly extract one of the methods to verify:

How to clone a list in python

As you can see, the lists we copied at this time are all independent and are not affected by the original list at all. However, have you noticed my title? Can be used when the list is an immutable data type. At this time we still give a counterexample to illustrate:

How to clone a list in python

At this point you will find that this seems to be somewhat similar to the result of using assignment (=), but it is different. In fact, when we use the above copy lists, it implements a shallow copy. Shallow copy is actually a bit more advanced than assignment, that is, it will copy all the values ​​in the list to the new object. However, if the value in the list is variable data (list, dictionary, function, class, etc.), it will only copy one Quote.

Deep copy

So, how should we copy if the copied list contains variable data? It's very simple. Where there is a shallow copy, there will be a deep copy. A deep copy means copying everything to the new object, which relieves you of all worries.

How to clone a list in python


The above is the detailed content of How to clone a list in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to get file extensionNext article:How to get file extension