Python List copy()

In this tutorial, we will learn about the Python List copy() method with the help of examples.

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

Example

# mixed list
prime_numbers = [2, 3, 5]

# copying a list
numbers = prime_numbers.copy()


print('Copied List:', numbers)

# Output: Copied List: [2, 3, 5]

1. Syntax of List copy()

The syntax of the copy() method is:

new_list = list.copy()

2. copy() parameters

The copy() method doesn’t take any parameters.

3. Return Value from copy()

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

4. Example: Copying a List

# mixed list
my_list = ['cat', 0, 6.7]

# copying a list
new_list = my_list.copy()


print('Copied List:', new_list)

Output

Copied List: ['cat', 0, 6.7]

If you modify the new_list in the above example, my_list will not be modified.

5. List copy using =

A list can be copied using the = operator. For example,

old_list = [1, 2, 3]
new_list = old_list

The problem with copying lists in this way is that if you modify new_listold_list is also modified. It is because the new list is referencing or pointing to the same old_list object.

old_list = [1, 2, 3]

# copy list using =
new_list = old_list


# add an element to list
new_list.append('a')

print('New List:', new_list)
print('Old List:', old_list)

Output

Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']

However, if you need the original list unchanged when the new list is modified, you can use the copy() method.

Related tutorial: Python Shallow Copy Vs Deep Copy

6. Example: Copy List Using Slicing Syntax

# shallow copy using the slicing syntax

# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing
new_list = list[:]


# Adding an element to the new list
new_list.append('dog')

# Printing new and old list
print('Old List:', list)
print('New List:', new_list)

Output

Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']