Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python List copy()

copy() in Python List

 

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.

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


#copy() in python list

myList = [ 129442 ]

#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


# “=” in python list

myList = [ 129442 ]

#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]