Using the copy module in Python to copy a list

Source: Internet
Author: User
This article mainly introduces how to copy a list using the copy module in Python. This article describes how to copy a simple list and how to copy a complex list, for more information, see reference. In Python, values stored in a variable are referenced in addition to values of the basic type. Therefore, you must be careful when using them. The following is an example:

Problem Description: A list is known to survive into a new list. the list element is the copy of the original list.

The code is as follows:


A = [1, 2]
B =


In fact, this method does not actually generate a new list, and B points to the object that a points. In this way, if the elements a or B are modified, the values of a and B change at the same time.

Solution:

The code is as follows:


A = [1, 2]
B = a [:]


In this way, modifying a has no effect on B. Modifying B has no effect on.

However, this method is only applicable to simple lists, that is, all elements in the list are of the basic type. if the list element still exists, this method is not applicable. This is because, for example, a [:], only generates a new list of column table element values. if the list element is also a list, for example, a = [1, [2], then this replication only copies the reference of [2] for element [2], but does not generate a new list copy of [2. To prove this, the test procedure is as follows:

The code is as follows:


>>> A = [1, [2]
>>> B = a [:]
>>> B
[1, [2]
>>> A [1]. append (3)
>>>
[1, [2, 3]
>>> B
[1, [2, 3]


It can be seen that the modification to a affects B. To solve this problem, you can use the deepcopy function in the copy module. The modification test is as follows:

The code is as follows:


>>> Import copy
>>> A = [1, [2]
>>> B = copy. deepcopy ()
>>> B
[1, [2]
>>> A [1]. append (3)
>>>
[1, [2, 3]
>>> B
[1, [2]


Sometimes it is very important to know this, because you may need a new list and operate it without affecting the original list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.