How to Copy a List in Python


In this article, we show how to copy a list in Python.

Sometimes it is important to be able to make a copy of a list in Python code. One example where this can be necessary is if you have an original list, but you want to delete all occurrences of a certain value or values. It's better to remove all the values from the list and store all the wanted leftover elements into a new list. We can then copy this new list into the original list where we deleted elements from. So this is just one example where copying a list is practical and useful.

So to make a copy of a list in Python, we use the following code below.

So we have a list, list1, which has 4 elements.

Then we have another list, list2, which is an empty list.

We then show the contents of both of these lists.

You can see that list1 has the contents of the numbers 1-4 and list2 has no contents.

We then make a copy of list1 by using the copy() function and we set it equal to list2. list2 now is a copy of list1, meaning it has all the same identical elements.

We then output list2, and you can see that it has all the same identical elements as list1.

And this is how you can copy a list in Python.

Related Resources

How to Get the Number of Items in a List in Python

How to Get the Last Item in a List in Python

HTML Comment Box is loading comments...