English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico Python

Controle de fluxo Python

Função no Python

Tipos de Dados do Python

Operações de arquivos Python

Objetos e classes Python

Data e hora Python

Conhecimentos avançados Python

Manual de referência Python

Métodos e exemplos de uso da função copy() da lista Python

Python list methods

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

listcan be copied using=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_list, old_list will also be modified.

old_list = [1, 2, 3]
new_list = old_list
# Add an element to the list
new_list.append('a')
print('New list:', new_list)
print('Old list:', old_list)

When running the program, the output is:

New list: [1, 2, 3, 'a'
Old list: [1, 2, 3, 'a'

However, if you need to keep the original list unchanged when modifying the new list, you can use the copy() method. This is called shallow copy.

The syntax of copy() is:

new_list = list.copy()

copy() parameters

copy() has no parameters.

copy() return value

The copy() function returns a list. It does not modify the original list.

Example1: Copy list

# Mixed list
list = ['cat', 0, 6.7]
# Copy a list
new_list = list.copy()
# Add an element to the new list
new_list.append('dog')
# Print the new and old lists
print('Old list: ', list)
print('New list: ', new_list)

When running the program, the output is:

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

As you can see, even if the new list is modified, the old list remains unchanged.

You can also achieve the same result using slicing:

Example2: Shallow list copy using slicing

# Mixed list
list = ['cat', 0, 6.7]
# Copy a list using slicing
new_list = list[:]
# Add an element to the new list
new_list.append('dog')
# Print the new and old lists
print('Old list: ', list)
print('New list: ', new_list)

After running, the output result is:

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

Python list methods