Copying lists

Published

2023-08-01

Copying lists

We’ve seen elsewhere that the following simply gives another name to a list.

>>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta']
>>> lst_2 = lst_1
>>> lst_1.sort()
>>> lst_2
['alpha', 'beta', 'delta', 'epsilon', 'gamma']

However, there are times when we really mean to make a copy. The .copy() method returns a shallow copy of a list.

>>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta']
>>> lst_2 = lst_1.copy()
>>> lst_1.sort()
>>> lst_2
['gamma', 'epsilon', 'delta', 'alpha', 'beta']

We can copy a list using a slice.

>>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta']
>>> lst_2 = lst_1[:]  # slice
>>> lst_1.sort()
>>> lst_2
['gamma', 'epsilon', 'delta', 'alpha', 'beta']

There’s another way we can copy a list: using the list constructor. The list constructor takes some iterable and iterates it, producing a new list composed of the elements yielded by iteration. Since lists are iterable, we can use this to create a copy of a list.

>>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta']
>>> lst_2 = list(lst_1)  # using the list constructor
>>> lst_1.sort()
>>> lst_2
['gamma', 'epsilon', 'delta', 'alpha', 'beta']

So now we have three ways to make a copy of a list:

  • By using the .copy() method
  • By slicing (lst_2 = lst_1[:])
  • By using the list constructor (lst_2 = list(lst_1))

Fun fact: Under the hood, .copy() simply calls the list constructor to make a new list.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).