copy() of Lists in Python

copy() of Lists in Python

The copy() method returns the copy of the list in python.

When we use the “=” sign to copy the list, if we modify the copied list then changes are also reflected back in the original list. So here we have to create a shallow copy of the list such that when we modify something in the copied list, changes are not reflected back in the original list.

Copy of sets in python

copy() of Lists in Python

In Python, you can create a copy of a list using the copy() method or by using slicing. You can use the copy() method to create a shallow copy of a list. A shallow copy means that the new list will contain references to the same objects as the original list.

Python List copy()

Syntax :


copyList = myList.copy()


Return Type :

The copy() method returns a shallow copy of the list in python.

Using the copy() method

Run
#copy() in python list

myList = [ 1, 2, 9, 4, 4, 2 ]

#all the values of myList is copied to the copyList
copyList = myList.copy()
print("Before Adding Element")
print(myList)
print(copyList)

#modifying copied list
copyList.append(10)

#changes is reflected in only copyList not in myList
print("After adding new element in copyList")
print(myList)
print(copyList)
Output :

Before Adding Element
[1, 2, 9, 4, 4, 2]
[1, 2, 9, 4, 4, 2]

After adding new element in copyList
[1, 2, 9, 4, 4, 2]
[1, 2, 9, 4, 4, 2, 10]

Using  ” = ”  Operator

Run
# "=" in python list

myList = [ 1, 2, 9, 4, 4, 2 ]

#all the values of myList is assigned to the copyList
copyList = myList
print("Before Adding Element")
print(myList)
print(copyList)

#modifying copied List
copyList.append(10)

#changes is reflected in only copyList not in myList
print("After adding new element in copyList")
print(myList)
print(copyList)
Output :

Before Adding Element
[1, 2, 9, 4, 4, 2]
[1, 2, 9, 4, 4, 2]

After adding new element in copyList
[1, 2, 9, 4, 4, 2, 10]
[1, 2, 9, 4, 4, 2, 10]

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription