How To Clone or Copy a List in Python

How To Clone or Copy a List in Python

There are a variety of options for copying/cloning a list in Python

Image for postPhoto by Kelly Sikkema on Unsplash

Working with lists is a bit different than primitive data types because setting your new variable equal to the existing one will create a reference rather than a standalone copy.

The following will illustrate this:

a = 4b = aa = 5print(a,b) # 5,4a = [1,2]b = aa.append(3)print(a,b) # [1,2,3] [1,2,3]

Notice that when appending to list a, our new list b was affected as well. So back to our original question: How do we clone or copy a list?

Define a New List

A straightforward method is to use the list() function to define a new list.

a = [1,2]b = list(a)a.append(3)print(a,b) # [1,2,3] [1,2]

Slice Notation

Python?s slice notation is a mechanism for returning a specified portion of a list. By omitting the start (before colon) and end (after colon) indexes, the full list is returned and subsequently assigned to the new variable.

a = [1,2]b = a[:]a.append(3)print(a,b) # [1,2,3] [1,2]

.copy() Method

Importing the copy library using the .copy() method will perform a shallow copy, behaving similarly to the aforementioned methods.

This method is also built-in to the list data type.

import copya = [1,2]b = copy.copy(a)a.append(3)print(a,b) # [1,2,3] [1,2]

.deepcopy() Method

Also from the copy library, the deepcopy() method predictably performs a deep copy, creating new elements of each list item.

This differs from a shallow copy in that each element is created anew as opposed to being shared.

To illustrate this, let?s create an object that?s included in our list and make a change to it.

import copyclass Test(): def __init__(self,n): self.n = n def __repr__(self): return str(self.n)obj = Test(5)a = [1,2,obj]b = copy.copy(a)c = copy.deepcopy(a)obj.n = 3print(a,b,c)# [1,2,3] [1,2,3] [1,2,5]

20