How to copy a list in Python

Image for post
Image for post

In programming, we work a lot with “list” data structure.
Some might run into the issues when working with “list” in Python.
Often times we would like to copy a list to another variable to reuse.
So how do we do that in Python?

1.Wrong way:

old_list = ["Donald is a guy", "Sunshine", 3]
new_list = old_list

If we do this, it actually create a new variable “new_list” which points to the exact memory of old_list.
So when we change the value of old_list or new_list, both list will be changed.

old_list.append("Parapara")
new_list.append("akaka")
print(new_list)
print(old_list)
Image for post
Image for post

2.Correct way:

To copy a list, we need to make a slice that includes the entire original list by omitting the first index and the second index ([:]).

old_list = ["Donald is a guy", "Sunshine", 3]
new_list = old_list[:]

Then we append new item to the list

old_list.append("Parapara")
new_list.append("akaka")
print(new_list)
print(old_list)

Let’s see the result:

Image for post
Image for post

That’s it.
Happy coding!!!

Originally published at https://dev.to on March 9, 2020.

Written by

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store