How to Copy a List in Python

Spread the love

There could be many reasons why do you want to copying a list. In this post, you will learn how to copy a list in python correctly.

Copying a List in Python –

Let’s say that I want to watch some movies on the weekend, so I created a movie list.

In [17]: my_wish_list = ['Avengers','Inception','The Dark Knight']

In [18]: my_wish_list
Out[18]: ['Avengers', 'Inception', 'The Dark Knight']

Now, Let’s say that my friend also like to watch these movies so he want to create a copy of this list. To do this he has to use the list slicing in python like this.

In [19]: friend_wish_list = my_wish_list[:]

In [20]: friend_wish_list
Out[20]: ['Avengers', 'Inception', 'The Dark Knight']

my_wish_list[:] tells python to give all the elements from the start of the list till end of the list.

Let’s see under the hood what is happening.

We can see that python created two separate wish list, one for me and one for my friend.

Now, let’s say I also want to watch The hangover movies but my friend does not want to watch it. He is interested in watching Free Guy. So we added these movies in our own list.

In [21]: my_wish_list.append('The Hangover')

In [22]: friend_wish_list.append('Free Guy')

And we can see that movies are added to their respective list. So copying a list using list slicing works as we aspect it to work.

But sometimes people try to copy a list using assignment operation which is a bad way to copy a list.

In [23]: my_wish_list = ['Avengers','Inception','The Dark Knight']

In [24]: friend_wish_list = my_wish_list

You can see that Instead of creating a separate list for me and my friend python created one single list. Now if I try to add the Hangover movies into my wish list, you will see that python will add this movie to my friend list also which he does not want to watch.

In [25]: my_wish_list.append('The Hangover')

In [26]: my_wish_list
Out[26]: ['Avengers', 'Inception', 'The Dark Knight', 'The Hangover']

In [27]: friend_wish_list
Out[27]: ['Avengers', 'Inception', 'The Dark Knight', 'The Hangover']

Rating: 1 out of 5.

Leave a Reply