Python List copy() - Creates Shallow Copy of List

The copy() method returns a shallow copy of a list. The copied list points to a different memory location than the original list, so changing one list does not affect another list.

If a new list is created from an existing list using the = operator then, a new list points to that existing list, and therefore, changes in one list will reflect in another list. The copy() method makes a shallow copy of the list so that the original list does not change when a new list is updated.

Syntax:

list.copy()

Parameters:

No parameters.

Return value:

Returns a new list.

The following example demonstrates the copy() method.

Example: copy()
cities = ['Mumbai', 'London', 'Paris', 'New York']
favCities = cities.copy()
print("Original list: ", cities)
print("Copied list: ", favCities)
Output
Original list: ['Mumbai', 'London', 'Paris', 'New York']
Copied list: ['Mumbai', 'London', 'Paris', 'New York']

When a change is made to the favCities list, cities list will be uneffected.

Example: copy()
favCities.append('Delhi')
print("Original list: ", cities)
print("Copied list: ", favCities)
Output
Original list: ['Mumbai', 'London', 'Paris', 'New York']
Copied list: ['Mumbai', 'London', 'Paris', 'New York', 'Delhi']

If we copy a list using = operator, the original list will also change whenever a change is made to the new list.

Example: Copy List using = Operator
cities = ['Mumbai', 'London', 'Paris', 'New York']
favCities = cities
cities.append('Delhi')
print("Original list: ", cities)
print("Copied list: ", favCities)
Output
Original list:  ['Mumbai', 'London', 'Paris', 'New York', 'Delhi']
Copied list:  ['Mumbai', 'London', 'Paris', 'New York', 'Delhi']

The following copies an integer list.

Example: copy()
nums = [1, 2, 3, 4, 5]
newnums = nums.copy()
newnums.append(6)

print("Original list: ", nums)
print("Copied list: ", newnums)
Output
Original list:  [1, 2, 3, 4, 5]
Copied list:  [1, 2, 3, 4, 5, 6]
Want to check how much you know Python?