Python list make copy

copy — Shallow and deep copy operations¶

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Return a shallow copy of x.

Raised for module specific errors.

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.

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

  • Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
  • Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
Читайте также:  Python if else in print

The deepcopy() function avoids these problems by:

  • keeping a memo dictionary of objects already copied during the current copying pass; and
  • letting user-defined classes override the copying operation or the set of components copied.

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

Shallow copies of dictionaries can be made using dict.copy() , and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:] .

Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__() . The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.

Discussion of the special methods used to support object state retrieval and restoration.

Источник

Python — Copy Lists

You cannot copy a list simply by typing list2 = list1 , because: list2 will only be a reference to list1 , and changes made in list1 will automatically also be made in list2 .

There are ways to make a copy, one way is to use the built-in List method copy() .

Example

Make a copy of a list with the copy() method:

Another way to make a copy is to use the built-in method list() .

Example

Make a copy of a list with the list() method:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

5 Ways to Copy a List in Python: Let’s Discover Them

Copy list in Python

It’s very common to copy a list in your Python programs. But, what should you absolutely know about copying lists?

How to copy a Python list?

Python provides multiple ways to copy a list depending on what your program needs to do with the existing list. You can use the assignment operator, the list copy method, the slice notation and shallow or deep copy.

This tutorial is designed to show you everything you need to know about copying lists in Python.

How to Make a Copy of a List in Python

I will start with a simple example to understand together how copying list works in Python.

After defining a list called numbers I use the assignment operator ( = ) to copy this list to a new list called new_numbers.

>>> numbers = [1,4,7,19,23] >>> new_numbers = numbers

Now I add a new element to the new_numbers list using the append method and verify the elements in both lists using the print function:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23, 34] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

For some reason even if we have added the new number to the new_numbers list only, both of our lists contain the new number.

We will use the built-in id function to print the memory address of our two lists and to make it more readable we will also use the hex function that provides an hexadecimal representation of an integer.

>>> hex(id(numbers)) '0x10d75e5a0' >>> hex(id(new_numbers)) '0x10d75e5a0'

Both variables point to the same memory address, so numbers and new_numbers points to the same list object. That’s why we see the new element in both of them.

So, how can we copy our list to a completely new object?

How to Create An Actual Copy of the Original List

Python provides the list copy method that allows to create a new list object from the one we copy.

Let’s use the copy method on our original list to create the list new_numbers:

Now we will append a number to the new list we have created and we will verify that the number is not present in the original list:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

This time the original list has not been changed by the append method applied to the new list.

And as confirmation we will also verify the memory location of both list objects:

>>> hex(id(numbers)) '0x10751d460' >>> hex(id(new_numbers)) '0x10761d9b0'

Different memory addresses for the two objects. That’s good!

Copying Using the Python Slice Notation

Another way to copy a Python list is with the slice notation.

The slice notation can be used to copy parts of a list into a new list or even the entire list by simply using the following expression:

Let’s apply it to our numbers list:

After adding another number to the new list you can see that the original list, once again, is unchanged:

>>> new_numbers.append(34) >>> print(numbers) [1, 4, 7, 19, 23] >>> print(new_numbers) [1, 4, 7, 19, 23, 34]

And that with the slice notation we have created a new list object:

>>> hex(id(numbers)) '0x105e92460' >>> hex(id(new_numbers)) '0x105f925f0'

And also this one is done! 🙂

Shallow Copy Vs Deep Copy

The difference between a shallow copy and a deep copy only applies to compound objects, in other words to objects that contain other objects.

Examples of compound objects are class instances and lists.

The Python copy module allows to create shallow copies and deep copies of objects. Below you can see the syntax for both types of copy:

SHALLOW COPY: new_object = copy.copy(original_object) DEEP COPY: new_object = copy.deepcopy(original_object)

With a shallow copy a new compound object is created (e.g. a list of lists) and references to the objects found in the original object are added to the new compound object.

In the next section we will see exactly how a shallow copy works.

In the meantime I want to make clear the difference between a shallow copy and a deep copy.

A deep copy creates a new compound object (e.g. a list of lists) then it also creates copies of the objects found in the original object and inserts them in the new compound object.

The definitions of shallow copy and deep copy will be a lot clearer in the next sections where we will see how they work in practice.

How to Make a Shallow Copy in Python

Let’s see how a shallow copy works with a list…

…try these commands in your Python shell to make sure the behaviour of shallow and deep copying is clear to you:

>>> import copy >>> numbers = [[1,2,3], [4,5,6], [7,8,9]] >>> new_numbers = copy.copy(numbers)

If I add an element to the new_numbers list the original list doesn’t change:

>>> new_numbers.append([10,11,12]) >>> numbers [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> new_numbers [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

This confirms that in the shallow copy a new compound object has been created. In other words the new compound object is not a reference to the original object.

But now, let’s try to update one element common between the original and the new list:

>>> new_numbers[0][0] = 4 >>> numbers [[4, 2, 3], [4, 5, 6], [7, 8, 9]] >>> new_numbers [[4, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

I have updated the first element of the first list object in the original list.

As you can see the element has been updated in both lists, the original and the new one.

That’s because we have used a shallow copy and hence the first element of the new_numbers list is just a reference to the first element of the numbers list ([1,2,3]).

We are using cookies to give you the best experience on our website.

You can find out more about which cookies we are using or switch them off in settings .

Источник

Оцените статью