Member-only story

How to copy a list in Python

Donald Le
2 min readMar 9, 2020

--

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)

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:

That’s it.
Happy coding!!!

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

--

--

Donald Le
Donald Le

Written by Donald Le

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

No responses yet