Python List copy() Method

Python list copy() method “returns a shallow copy of the list”.

Syntax

newList = list.copy()

Parameters

It does not take any arguments.

Return value

The copy() method returns a new list. It doesn’t modify the original list.

You have to provide the source list to copy the elements of that list.

Example 1: How to Copy a List

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
clonedList = targaryens.copy()

print(clonedList)

Output

Python List Copy Example

The copy() function returns a list. However, it doesn’t modify the original list.

Example 2: Copying and modifying a list

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']

clonedList = targaryens.copy()

print(clonedList)

print(targaryens)

targaryens.append('Daemon')

print('---After modified---')

print(targaryens)

print(clonedList)

Output

Copy and Modify List

Example 3: Copy List Using Slicing Syntax

Python slice() method is considered when we want to modify the list and also keep the copy of an original.

In this scenario, we copy the list and the reference. This process is also called cloning. The technique takes about 0.039 seconds and is the fastest technique.

targaryens = ['Aegon', 'Daenerys', 'Aemon', 'Aeris', 'Rhaegar', 'Viserys']
sliceCopy = targaryens[:]

print(sliceCopy)

Output

Shallow Copy of a List Using Slicing

Copy a list using =

You can use the “=” operator to copy the list. The only drawback to this method is that it does not create a shallow copy.

list = [11, 21, 19]

list_new = list


print("This is the new list: " + str(list_new))

list_new.append(46)

print("The new list after adding a new element: " + str(list_new))
print("The old list after adding a new element" + str(list))

Output

This is the new list: [11, 21, 19]
The new list after adding a new element: [11, 21, 19, 46]
The old list after adding a new element: [11, 21, 19, 46]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.