Copying lists
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.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.