Python List copy()

In this article, we will discuss about the usage details of copy() method of List in Python.

Table Of Contents

Introduction

The copy() method of a list, returns a shallow copy of list. It can be usefull, if we don’t want to modify the original list, then we can get a shallow copy of list, and make modifications on that. The original list will remain intact.

Syntax of List copy() method

newCopiedList = list.copy()

Parameters

  • It doesn’t accept any parameter.

Returns

Advertisements

It returns a shallow copy of the calling list object.

The returned copy of list, and the original list, both will have similar contents. But any modification in one list, will not impact the other list. Basically, they will not be linked to each other in any way.

Let’s see some examples.

Example of List copy() method

Suppose we have a list of numbers, and we created its copy using the copy() method,

listOfNumbers = [22, 11, 33, 44, 11, 55, 11, 88, 77]

# get a shallow copy of list
newList = listOfNumbers.copy()

print('New List : ', newList)

Output:

New List :  [22, 11, 33, 44, 11, 55, 11, 88, 77]

Content of new list is same as original list. Now let’s try to modify the newList object by sorting all the elements in new list i.e.

# Sort the new list
newList.sort()

print('New List : ', newList)
print('Original List : ', listOfNumbers)

Output:

New List :  [11, 11, 11, 22, 33, 44, 55, 77, 88]
Original List :  [22, 11, 33, 44, 11, 55, 11, 88, 77]

It sorted the numbers on new list only. There was no impact on the original list, it remained as it was eralier.

List copy() method vs = operator

If you try to copy a list using the assignment operator (=) instead of copy() function. Then any modification in one list will be reflected in the other list. For example,

listOfNumbers = [22, 11, 33, 44, 11, 55, 11, 88, 77]

# get a copy of list
newList = listOfNumbers

print('New List : ', newList)

# Sort the new list
newList.sort()

print('New List : ', newList)
print('Original List : ', listOfNumbers)

Output

New List :  [22, 11, 33, 44, 11, 55, 11, 88, 77]

New List :  [11, 11, 11, 22, 33, 44, 55, 77, 88]
Original List :  [11, 11, 11, 22, 33, 44, 55, 77, 88]

We sorted the new List object only, but it affected the original list also, because it was not a shallow copy. To create a shallow copy, always use the copy() method of List.

Summary

We learned about the copy() method of List in Python. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top