Python copy List Function

This Python method is used to shallow copy the items into a completely new list and the syntax of this function is

Lname.copy()

Python List copy Function Example

This function copies total items in a given list to a new. The below code duplicate a to new.

a = [10, 20, 30, 40]

print("Original : ", a)
new = a.copy()
print("After this method  : ", new)
Original :  [10, 20, 30, 40]
After this method :  [10, 20, 30, 40]

In this example, we declared the string elements, and then, we used this on it.

strFruits = ['Apple', 'Banana', 'Kiwi', 'Grape']

print("Original : ", strFruits)
newLi = strFruits.copy()
print("After    : ", newLi)
Python Copy List Function 2

TIP: Please refer to List and methods articles in Python.

This example shallow copies the items into a completely new.

Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]

print("Original : ", Fruits)
print("Original number : ", numbers)

New_Fruits = Fruits.copy()
print("\nNew : ", New_Fruits)

new_numbers = numbers.copy()
print("New Number : ", new_numbers)
Original :  ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
Original number :  [9, 4, -5, 0, 22, -1, 2, 14]

New :  ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
New Number :  [9, 4, -5, 0, 22, -1, 2, 14]

Let me use this on the Mixed elements.

Mix = ['apple',  1, 'Banana', 5, 'Kiwi', 'Mango']

print(Mix)
new = Mix.copy()
print(new)
['apple', 1, 'Banana', 5, 'Kiwi', 'Mango']
['apple', 1, 'Banana', 5, 'Kiwi', 'Mango']

In this program, we used it on the Nested.

nest = [[71, 222], [222, 13], [14, 15], [99, 77]]

print(nest)
new = nest.copy()
print(new)
[[71, 222], [222, 13], [14, 15], [99, 77]]
[[71, 222], [222, 13], [14, 15], [99, 77]]