How to Copy a List in Python
To copy a list in Python, you can use the [:] slice operator, the list() function, or the copy() function.
The following examples show how to copy a list in Python.
Using [:] Operator
We can use the [:] slice operator to copy a list.
Suppose we have the following list:
# Declare list of names
names = ["Anita", "Sanika", "Shubham", "Gaurav", "Namita", "Sushma"]
# Copy list
copy_list = names[:]
# Show copied list
print("Copied list:", copy_list)
Output: 👇️
Copied list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma']
In this example, we use the [:] slice operator to create a copy of the list names.
Using list() Function
We can use the list() function to copy a list.
Suppose we have the following list:
# Declare list of names
names = ["Anita", "Sanika", "Shubham", "Gaurav", "Namita", "Sushma"]
# Copy list
copy_list = list(names)
# Show copied list
print("Copied list:", copy_list)
Output: 👇️
Copied list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma']
In this example, we use the list() function to create a copy of the list names.
Using copy() Function
We can use the copy() function to copy a list.
Suppose we have the following list:
# Import copy module
import copy
# Declare list of names
names = ["Anita", "Sanika", "Shubham", "Gaurav", "Namita", "Sushma"]
# Copy list
copy_list = copy.copy(names)
# Show copied list
print("Copied list:", copy_list)
Output: 👇️
Copied list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma']
In this example, we use the deepcopy() function from the copy module to create a deep copy of the list names. This ensures that any nested lists are also copied, rather than just referencing the original nested lists.
Conclusion
In Python, there are several ways to copy a list:
- Using the [:] slice operator.
- Using the list() function.
- Using the copy() function from the copy module.
- Using the deepcopy() function from the copy module for nested lists.
Each method has its use case, and you can choose the one that best fits your needs.