AppDividend
Latest Code Tutorials

Python List Copy Example | How To Clone Or Copy A List

0

In this tutorial, we will see Python List Copy Example | How to clone or copy a List. Python copy() method returns a shallow copy of the list. Python inbuilt method copy() is used to copy all the items from one list to another list. This method takes around 1.488 seconds to complete. Python3 introduced a new method in Python lists called copy(), and it does exactly what you think it does. It copies the list into another list. One thing to remember that it is not available in Python2.

Python List Copy Example

In Python List Copy() Method, the original list unchanged when the new list is modified. This is called a shallow copy. The syntax of Python List Copy() method is following.

newList = list.copy()

You have to provide the source list to copy the elements of that list.

See the following example.

# app.py

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
clonedList = targaryens.copy()
print(clonedList)

The output is following.

Python List Copy Example

 

The copy() function returns a list. It doesn’t modify the original list.

Copy and Modify List

Let’s copy a list and then modify that list. See the below code.

# app.py

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
clonedList = targaryens.copy()
print(clonedList)
print(targaryens)
targaryens.append('Daemon')
print('---After modified---')
print(targaryens)
print(clonedList)

In the above code, first we have cloned the list, and then we have modified the source list which is targaryens. Then again we have printed both the list and see the output.

 

Copy and Modify List

You can see that an old list remains unchanged even when a new list is modified.

Shallow Copy of a List Using Slicing

If you do not know what is Python list slice, then check out Python Slice Notation Tutorial.

Python slice method is considered when we want to modify the list and also keep the copy of an original. In this scenario, we make a copy of the list itself, along with the reference. This process is also called cloning. The technique takes about 0.039 seconds and is the fastest technique.

See the below code.

# app.py

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
sliceCopy = targaryens[:]
print(sliceCopy)

Check the below output.

Shallow Copy of a List Using Slicing

 

Using the extend() method

The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.

See the below code.

# app.py

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']

def Cloning(list): 
    copy = [] 
    copy.extend(list) 
    return copy 

extendedCopy = Cloning(targaryens) 
print("Original List:", targaryens) 
print("After Cloning:", extendedCopy)

The output is following.

How To Clone Or Copy A List

 

Using list comprehension

The method of a list comprehension can be used to copy all the items individually from one list to another. It takes around 0.217 seconds to complete. See the below code.

# app.py

def Cloning(list):
  compreList = [i for i in list]
  return compreList

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
compreList = Cloning(targaryens)
print("Original List:", targaryens)
print("After Cloning:", compreList)

The output is following.

 

Using list comprehension

Using the list() method

Python list() is the simplest method of cloning a list by using the builtin function list(). It takes about 0.075 seconds to complete. See the below code.

# app.py

def Cloning(l):
  cloneList = list(l) 
  return cloneList
  
targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
cloneList = Cloning(targaryens)
print("Original List:", targaryens)
print("After Cloning:", cloneList)

The output is following.

Using the list() method

Shallow and deep copy operations in Python

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 elements, a copy is sometimes needed so one can change a copy without changing the another. The copy module provides generic shallow and deep copy operations. We need to import that at the start of the program. See the example of shallow copy using the copy.copy() method.

# app.py

import copy

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
clonedList = copy.copy(targaryens)
print(clonedList)
print(targaryens)

targaryens.append('Daemon')
print('---After modified---')
print(targaryens)
print(clonedList)

See the output.

Shallow and deep copy operations in Python

The difference between depp and shallow copying is only relevant for the compound objects. Compund objects are the objects that contain other objects, like lists or class instances.

  • shallow copy constructs the new compound object and then to the extent possible, it inject references to the objects found in an original.
  • deep copy constructs the new compound object and then, recursively, inserts copies into it of the objects found in the original.

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

  • Recursive objects (compound objects that, directly or indirectly, contain the reference to themselves) may cause a recursive loop.
  • Because deep copy copies everything, it may copy too much, such as the data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

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

Now, see the deepcopy() method example.

# app.py

import copy

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
clonedList = copy.deepcopy(targaryens)
print('Original List:', targaryens)
print('Cloned List:', clonedList)
targaryens.append('Daemon')
print('---After modified---')
print('Original List:', targaryens)
print('Cloned List:', clonedList)

The output is following.

 

How To Clone Or Copy A List in Python

Finally, Python List Copy Example | How To Clone Or Copy List Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

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