Python list copy Function | copying(cloning) a List examples

Python list copy method returns a copy of the specified list. It returns a shallow copy of the list.

What is a shallow copy?

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. So, if you need the original list unchanged when the new list is modified, you can use copy() method.

Techniques to shallow copy :

  • Using copy.copy()
  • Using list.copy()
  • Using slicing

Syntax

Parameter Values

It don’t return any value and doesn’t modify the original list.

Python list copy Function Examples

Copy/clone List example

In the example Copying the fruits list. its copy list without changing original list.

Output:

[‘apple’, ‘banana’, ‘cherry’, ‘orange’]

Python list copy deep

Techniques to deep copy :

  • Using copy.deepcopy()
  • Using “=” operator

Example of deep copy

Output:

The new list created using copy.deepcopy() : [1, 2, 3, 4, 5]
The new list created using = : [1, 2, 3, 4, 5]
The old list : [1, 2, 3, 4, 5]

Copy list by value in Python

A way to copy a list by value:

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

Deep Copy vs Shallow copy

The difference between Deep Copy vs Shallow copy is Deep copy means if we modify any of the lists, changes are reflected in both the list as they point to the same reference. Whereas in shallow copy, when we add an element in any of the lists, only that list is modified.

Q: How to python copy list of list?

Answer: Same as above you can use copy function to copy list of list:

Output: [[1, 2], [3, 4]]

Q: What are the options to clone or copy a list in Python?

Answer: You can Copy the list with various ways like:

You can use the builtin list.copy() method (available since Python 3.3):

You can slice it:

You can use the built in list() function:

You can use generic copy.copy():

This is a little slower than list() because it has to find out the datatype of old_list first.

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

Complete Example

Output:

Python list copy Function

Do comment if you have any example, doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.