• Janarthanan Soundararajan

The Best Way to Copy a List in Python - Learn Python.

Updated: Jun 28

Everything in Python is an object. An object may be mutable or immutable. In Python, lists are mutable data structures. Assigning the list to a variable will not copy the list. So in this post, we will see the best way to copy the Python lists.


Assignment Operator

Assigning the list in the one variable to another variable seems we're coping. But not, both lists will point the same memory location(reference), if we use the assignment operator to copy the list. Doing changes in the new list will reflect in the original one.


list_one = [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two = list_one

print(list_two)
# [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two[0] = 8

print(list_two)
# [8, 2, 3, [4, 5, 6, [7, 8]]]

print(list_one)
# [8, 2, 3, [4, 5, 6, [7, 8]]]


List Slicing

List slicing will swallow copy the list. It is safe only for one dimension. Doing changes in the inner nested list will reflect in the original.

list_one = [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two = list_one[:]
list_two[0] = 8

print(list_two)
# [8, 2, 3, [4, 5, 6, [7, 8]]]

print(list_one)
# [1, 2, 3, [4, 5, 6, [7, 8]]] Didn't reflect

list_two[3][0] = 10

print(list_two)
# [8, 2, 3, [10, 5, 6, [7, 8]]]

print(list_one)
# [1, 2, 3, [10, 5, 6, [7, 8]]] Changes are reflected

'list()' or 'list_variable.copy()' or 'list.copy(list_variable)'

Using the 'list()' function is the same as doing swallow copy using the list slicing.

list_one = [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two = list(list_one)

list_two[0] = 8

print(list_two)
# [8, 2, 3, [4, 5, 6, [7, 8]]]

print(list_one)
# [1, 2, 3, [4, 5, 6, [7, 8]]] Didn't reflect
list_two[3][0] = 10

print(list_two)
# [8, 2, 3, [10, 5, 6, [7, 8]]]

print(list_one)
# [1, 2, 3, [10, 5, 6, [7, 8]]] Changes are reflected

Using 'list_one.copy()' and list.copy(list_one) will give the same result showed in the above snippet.

Nothing works, right? Then what is the solution?

The above all methods will swallow copy the list. To solve the problem we should deep copy the list. The solution comes with the Python standard library. Yes, we can use the 'copy' library from the Python standard library.


copy.deepcopy()

The copy.deepcopy() method will perfectly deep copy the list value from one variable to a new one. Doing changes to the new list will not reflect the original one.

importcopy

list_one = [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two = copy.deepcopy(list_one)

list_two[0] = 8

print(list_two)
# [8, 2, 3, [4, 5, 6, [7, 8]]]

print(list_one)
# [1, 2, 3, [4, 5, 6, [7, 8]]]

list_two[3][0] = 10

print(list_two)
# [8, 2, 3, [10, 5, 6, [7, 8]]]print(list_one)# [1, 2, 3, [4, 5, 6, [7, 8]]]

I hope this blog post is helpful. Check my other posts related to Python in the following link.

https://www.techaaroorian.com/blogs/categories/python

Thank you for reading :)


205 views

©2020 by Techaaroorian.

  • Pinterest
  • Twitter Social Icon
  • Facebook
  • YouTube