Python language basics 45: 3 ways to copy a list
September 6, 2015 1 Comment
Introduction
In the previous post we discussed how to slice a collection. We saw how you could create another collection from the original by extracting a range of it.
In this post we’ll describe various ways to create a copy of a list.
Producing copies
Consider the following list of cities:
cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]
Slicing
The first technique will reuse collection slicing we discussed previously. As mentioned you can ignore either the start or the end index for the range. In fact you can ignore both which will extract all the values from a list:
cities_copy = cities[:]
Let’s see if they are equal by value and by reference as we saw in this post:
print(cities == cities_copy) print(cities is cities_copy)
This prints True and False respectively.
Strings are immutable objects. Changing one of the values in either of the lists will not affect the values in the other list:
cities_copy[0] = "Washington" print(cities) print(cities_copy)
[‘Stockholm’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’]
[‘Washington’, ‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’, ‘Zürich’]
In case the contained objects are mutable, such as other lists, dictionaries – like we saw here – or your custom objects, which we haven’t seen so far, this won’t be the case. All techniques you see here create shallow copies with all its implications for mutable objects.
The list constructor
The list constructor function accepts another list and creates an independent copy. The reference and value equality tests will return the same as above:
cities_copy = list(cities)
The copy function
The copy function operates on the list and essentially performs the same as the slicing method above. The reference and value equality tests will return the same as above:
cities_copy = cities.copy()
Read the next part here.
Read all Python-related posts on this blog here.
When I tried below function from the article
cities_copy = cities.copy()
it give me error
cities_copy = cities.copy()
AttributeError: ‘list’ object has no attribute ‘copy’