Python language basics 45: 3 ways to copy a list


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"]


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"


[‘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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Python language basics 45: 3 ways to copy a list

  1. hardik says:

    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’

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: