Python – Find List Shallow Copy – copy() Function with Examples

copy() function is used to make a shallow copy of a list into another list. We can simply cop a list into another list by simply applying using the (=) assignment operator.
list1 = [1, 2, 3]
list2 = list1

But there is a problem with this type of copy. If we change the value of list1, the value of list2 will automatically change. That mean the list2 is also pointing to the list1 content. So, what we we do to change this behaviour. When we have to create a totally new copy of a list, we use copy() method. This method use the element of a list and make a list base on those elements this type of copy called shallow copy.

Syntax of copy() Function

The syntax of copy() function in Python is:



Parameters of copy() Function in Python

There is no argument pass to copy() method.



copy() function is only available and compatible with Python 3.x. This function is one of python list methods.


Return Value of copy() Function in Python

copy() function returns a shallow copy of a list.


Python copy() Function Example 1

Here we have a list with few colors (red, green, blue) and goal is to make the copy of this list and add another in the list so we can check that second color list does not point to the previous color list.

# a colors list
color1 = ['red', 'green', 'blue']
#making a copy of
# color1 into color2
color2 = color1.copy()
#Adding yellow color in color2
#Print the both color lists
print('First color list', color1)
print('Second color list', color2)

First color list ['red', 'green', 'blue']
Second color list ['red', 'green', 'blue', 'yellow']