Python List copy() Method

Copies the list shallowly

Usage

The copy() method returns the Shallow copy of the specified list.

Syntax

list.copy()

Basic Example

Example: Create a copy of list ‘L’

L = ['red', 'green', 'blue']
X = L.copy()
print(X)    # ['red', 'green', 'blue']

copy() vs Assignment statement

Assignment statement does not copy objects. For example,

Example:

old_List = ['red', 'green', 'blue']
new_List = old_List
new_List[0] = 'xx'
print(old_List)     # ['xx', 'green', 'blue']
print(new_List)     # ['xx', 'green', 'blue']

When you execute new_List = old_List, you don’t actually have two lists. The assignment just makes the two variables point to the one list in memory.

copy method vs assignment statement

So, when you change new_List, old_List is also modified.

If you want to change one copy without changing the other, use copy()method.

Example:

old_List = ['red', 'green', 'blue']
new_List = old_List.copy()
new_List[0] = 'xx'
print(old_List)     # ['red', 'green', 'blue']
print(new_List)     # ['xx', 'green', 'blue']

Equivalent Method

Assigning a slice of the entire list to a variable is equivalent to copy() method.

Example: Copy list with start-to-end slice

L = ['red', 'green', 'blue']
X = L[:]
print(X)    # ['red', 'green', 'blue']