Python Program to Copy a List

Python Program to Copy a List | Python provides built-in methods and functions to copy one list to another. Usually, it copies one list to another and returns the third list as an output. There are many ways to perform a python copy list. Also see:- How to Compare Two Lists in Python

We will see these below Python program examples:-

  1. Python program to copy variable
  2. How to copy one list to another in Python
  3. Deep copy vs shallow copy in python
  4. Python program to deep copy list
  5. Python deep copy without import
  6. Python program to shallow copy list
  7. Python copy list without reference

Python Program to Copy Variable

Copying a variable can be done by the “=” operator, we may think that it creates another object but it just creates a new variable without any new object. Observe the below code old list and new list are the same, the new list has been copied from the old list, and also observe that the id’s of both the list are also the same which means there is no object created for the new variable.

list1 = [[1, 2, 3]]
list2 = list1

print('Old List:', list1)
print('New List:', list2, '\n')

print('ID of Old List:', id(list1))
print('ID of New List:', id(list2))

Output:

Old List: [[1, 2, 3]]
New List: [[1, 2, 3]]

ID of Old List: 140595009776960
ID of New List: 140595009776960

How to Copy One List to Another in Python

There are many methods to copy one list to another let us study one by one.

Python Program to Copy a List using Slicing()

Slicing is the fast and easiest way to clone a list. We use this method when we want to modify the list and also keep the original list.

def clone(list1):
   list_copy = list1[:]
   return list_copy

list1 = [1,2,3]
list2 = clone(list1)
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, 3]
List2: [1, 2, 3]

Python Copy List using extend()

The extend() method appends the list to another list.

def clone(list1):
   list_copy = []
   list_copy.extend(list1)
   return list_copy

list1 = [1,2,3]
list2 = clone(list1)
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, 3]
List2: [1, 2, 3]

Python Copy List using list()

We can copy a list by using the list() method also this is a built-in method in python.

def clone(list1):
   list_copy = list(list1)
   return list_copy

list1 = [1,2,3]
list2 = clone(list1)
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, 3]
List2: [1, 2, 3]

Deep Copy vs Shallow Copy in Python

Lets us now study the difference between shallow copy and deep copy.
Shallow copy stores the references of the object to the original memory whereas deep copy stores the copy of the object value. A shallow copy is faster than a deep copy.

The changes made in the new object reflect the original object in shallow copy but do reflect any changes in deep copy.

Shallow copy stores the copy of the original object and points the references to the object whereas In deep copy stores the copy of the original object and recursively calls the original object.

Python Program to Deep Copy List

Now we will demonstrate deep copy by importing the copy module. When you make changes to the list it does not affect the original list.

import copy
list1 = [1, 2, 4]
list2 = copy.deepcopy(list1)
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, 4]
List2: [1, 2, 4]

Python Deep Copy Without Import

Now we try to do deep copy without using the copy module, In the below code the main function is needed to create a deep copy of the JSON structure.

def main(data):
   if isinstance(data, dict):
      res = {}
      for key, value in data.items():
         res[key] = main(value)
   elif isinstance(data, list):
      res = []
      for item in data:
         res.append(main(item))
   elif isinstance(data, (int, float, type(None), str, bool)):
      res = data
   else:
      raise ValueError("Unrecognized type for main function")
   return res

data = [3, 5, 4, 7]
print("List1:", data)
print("List2:", main(data))

Output:

List1: [3, 5, 4, 7]
List2: [3, 5, 4, 7]

Python Program to Shallow Copy List

Now, let’s demonstrate the working of shallow copy by importing copy module, unlike deep copy for the shallow copy we use the copy() method.

import copy
list1 = [1, 2, [3,5], 4]
list2 = copy.copy(list1)
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, [3, 5], 4]
List2: [1, 2, [3, 5], 4]

Python Copy List without Reference

Here, we will not create any reference object we just copy from the only list to another, both the list refers to the same memory you can check this by id().

list1 = [1,2,3]
list2 = list1.copy()
print("List1:", list1)
print("List2:", list2)

Output:

List1: [1, 2, 3]
List2: [1, 2, 3]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *