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

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemple de copy() de la liste Python

Python list methods

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

listcan be copied using=Operators. 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 the original list to remain unchanged while modifying the new list, you can use the copy() method. This is called a shallow copy.

The syntax of the copy() method 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 = ['猫', 0, 6.7]
# Copy a list
new_list = list.copy()
# Add an element to the new list
new_list.append('狗')
# Print the new and old lists
print('Old list: ', list)
print('New list: ', new_list)

When running the program, the output is:

Old list: ['猫', 0, 6.7]
New list: ['猫', 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