Python: Copy List

Copy List Using = Operator

A list can be copied using the = operator.

old_list = ['a','b','c']
new_list = old_list
print(new_list)

Output: ['a', 'b', 'c']

The problem with copying lists in this way is that if we modify new_list, old_list is also modified. It is because the new list is referencing or pointing to the same old_list object.

Copy List using copy () method

Sometimes we want to modify new list with the new values and keep the old list unchanged and vice-versa. In Python there are two ways to create copy.

1. Shallow Copy

It creates a new object which stores the reference of the original elements. If we modify any of the nested list elements, changes are reflected in both the list as they point to the same reference.

Techniques to Shallow Copy:

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

Create a copy using shallow copy:

import copy
list_1 = [[1, 2, 3], [4, 5, 6]]
list_2 = copy.copy(list_1)
print("Old list:", list_1)
print("New list:", list_2)

Output:

Old list: [[1, 2, 3], [4, 5, 6]]
New list: [[1, 2, 3], [4, 5, 6]]

In this example, we have created a nested list and then shallow copy it using copy () method i.e. it will create new and independent object with same content.

Adding a new object using shallow copy:

import copy

list_1 = [[1, 2, 3], [4, 5, 6]]
list_2= copy.copy(list_1)
list_1[0][0] ='A'
print("Old list:", list_1)
print("New list:", list_2)

Output:

Old list: [['A', 2, 3], [4, 5, 6]]
New list: [['A', 2, 3], [4, 5, 6]]

In this example, we have made changes to list_1. But both old list and new list were modified. This is because, both lists share the reference of same nested objects.

2. Deep Copy:

In Deep Copy when we add an element in any of the lists, only that list is modified.

Techniques to Deep Copy:

  • Using copy.deepcopy()

Create a copy using deep copy:

import copy

old_list = [['a','b','c'], ['d', 'e','f' ]]
new_list = copy.deepcopy(old_list)

print("Old list:", old_list)
print("New list:", new_list)

Output:

Old list: [['a', 'b', 'c'], ['d', 'e', 'f']]
New list: [['a', 'b', 'c'], ['d', 'e', 'f']]

In this example, deep copy () function has been used to create copy which looks similar.

Adding a new object using deep copy:

import copy

old_list = [['a','b','c'], ['d', 'e','f' ]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'B'

print("Old list:", old_list)
print("New list:", new_list)

Output:

Old list: [['a', 'b', 'c'], ['B', 'e', 'f']]
New list: [['a', 'b', 'c'], ['d', 'e', 'f']]

In this example, we can see that when we assign a new value to old list only old list is modified. This shows that both the list is independent.

Tags