Last modified: Oct 31, 2024 By Alexander Williams
Python Copy List: Complete Guide with Examples
Copying lists in Python is useful when you need to work with duplicates without affecting the original list.
This guide covers several methods to copy a list with examples and explanations.
Using Slicing to Copy a List
One of the simplest ways to copy a list is with slicing. This creates a new list with the same elements.
fruits = ["apple", "banana", "cherry"]
new_fruits = fruits[:]
print(new_fruits)
['apple', 'banana', 'cherry']
Slicing fruits[:]
returns a new list new_fruits
that is independent of the original.
Using the list() Function
The list()
function is another easy way to create a copy of a list.
It’s useful when you want a new list object, not a reference to the original list.
fruits = ["apple", "banana", "cherry"]
new_fruits = list(fruits)
print(new_fruits)
['apple', 'banana', 'cherry']
Using list(fruits)
creates a new list new_fruits
with the same contents.
Using the copy() Method
The copy()
method is available in Python lists to create shallow copies.
This is effective when you don’t need a deep copy of nested lists.
fruits = ["apple", "banana", "cherry"]
new_fruits = fruits.copy()
print(new_fruits)
['apple', 'banana', 'cherry']
With copy()
, new_fruits
is an independent list from fruits
.
Using the copy Module for Deep Copies
If you’re copying a list of lists or other nested objects, you’ll need a deep copy to avoid references to the original.
The copy.deepcopy()
function from the copy
module is perfect for this.
import copy
nested_list = [[1, 2, 3], [4, 5, 6]]
new_nested_list = copy.deepcopy(nested_list)
print(new_nested_list)
[[1, 2, 3], [4, 5, 6]]
Using copy.deepcopy()
creates a new copy of nested_list
without linking to the original list.
Using List Comprehension
List comprehensions are useful for copying lists while applying transformations.
This method is best for creating modified copies.
fruits = ["apple", "banana", "cherry"]
new_fruits = [fruit for fruit in fruits]
print(new_fruits)
['apple', 'banana', 'cherry']
In this example, [fruit for fruit in fruits]
returns a new list identical to fruits
.
Conclusion
With options like slicing
, list()
, and copy()
, Python makes it easy to copy lists.
Learn more about list manipulation in Adding a List to Another List in Python.
Using these methods, you can confidently manage lists in Python without accidental modifications.