Open In App

Python List copy() Method

Last Updated : 27 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The copy() method in Python is used to create a shallow copy of a list. This means that the method creates a new list containing the same elements as the original list but maintains its own identity in memory. It’s useful when you want to ensure that changes to the new list do not affect the original list and vice versa. Example:

[GFGTABS]
Python

a = [1, 2, 3]

b = a.copy()

print('a:', a)
print('b:', b)


[/GFGTABS]

Output

a: [1, 2, 3]
b: [1, 2, 3]

Explanation: a.copy() creates a shallow copy of the list a.

Syntax

list.copy()

Parameters:

  • copy() method doesn’t take any parameters.

Return Type: Returns a shallow copy of a list.

Examples of copy() Methods

Example 1: Modifying the Copied List

A value is appended in copy list but the original list remains unchanged. This shows that the lists are independent.

[GFGTABS]
Python

a = [1, 2, 3]

b = a.copy()
b.append(4)

print('a:', a)
print('b:', b)


[/GFGTABS]

Output

a: [1, 2, 3]
b: [1, 2, 3, 4]

Explanation: After appending 4 to b, the original list a remains unchanged. This shows that a and b are independent lists.

Example 2: Copying a List of Lists (Shallow Copy)

Even though copy() creates a new list but it is a shallow copy. Modifying the inner list in copied list also affects original list because both lists reference the same inner lists.

[GFGTABS]
Python

a = [[1, 2], [3, 4]]
b = a.copy()

b[0][0] = 100

print("a:", a)
print("b:", b)


[/GFGTABS]

Output

a: [[100, 2], [3, 4]]
b: [[100, 2], [3, 4]]

Explanation: Although a and b are separate lists, the nested lists inside them are still shared. Modifying a nested item in b also affects a. This is what makes it a shallow copy.

Example 3: Copying a List with Mixed Data Types

In the below example, ‘b’ is a shallow copy of a list with mixed data types (integers, strings, lists, and dictionaries). After modifying the nested list inside copied list ‘b’ affects original list ‘a’ because it’s a shallow copy.

[GFGTABS]
Python

a = [1, 'two', 3.0, [4, 5], {'key': 'value'}]
b = a.copy()

b[3].append(6)

print("a:", a)
print("b:", b)


[/GFGTABS]

Output

a: [1, 'two', 3.0, [4, 5, 6], {'key': 'value'}]
b: [1, 'two', 3.0, [4, 5, 6], {'key': 'value'}]

Explanation: Even though a and b are different lists, they both reference the same inner list [4, 5]. So when 6 is appended to b[3], it also changes a[3].

Related Articles:


Next Article

Similar Reads