|
| Home |
|---|
Copying a list means creating another list that contains the same elements as the original list. This is useful when you want to modify a list without changing the original data.
Python provides several ways to copy a list. These include using the
copy() method, slicing, the list() constructor,
and loops.
If you assign one list variable to another variable directly, both variables will refer to the same list object.
list1 = [1,2,3]
list2 = list1
list2[0] = 100
print(list1)
print(list2)
[100, 2, 3]
[100, 2, 3]
Both variables refer to the same list, so modifying one affects the other. To avoid this problem, we create a copy of the list.
The copy() method creates a shallow copy of the list.
numbers = [1,2,3]
copy_numbers = numbers.copy()
print(copy_numbers)
[1, 2, 3]
colors = ["Red","Green","Blue"]
new_colors = colors.copy()
new_colors[0] = "Yellow"
print(colors)
print(new_colors)
['Red', 'Green', 'Blue']
['Yellow', 'Green', 'Blue']
List slicing can also create a copy of a list.
numbers = [10,20,30]
copy_numbers = numbers[:]
print(copy_numbers)
[10, 20, 30]
fruits = ["apple","banana","cherry"]
new_fruits = fruits[:]
new_fruits.append("orange")
print(fruits)
print(new_fruits)
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry', 'orange']
The built-in list() function can also be used to create
a copy of a list.
numbers = [5,10,15]
new_list = list(numbers)
print(new_list)
[5, 10, 15]
colors = ["Red","Blue"]
copy_colors = list(colors)
copy_colors.append("Green")
print(colors)
print(copy_colors)
['Red', 'Blue']
['Red', 'Blue', 'Green']
Another way to copy a list is by looping through the elements and adding them to a new list.
numbers = [1,2,3]
copy_numbers = []
for n in numbers:
copy_numbers.append(n)
print(copy_numbers)
[1, 2, 3]
colors = ["Red","Green","Blue"]
new_list = []
for color in colors:
new_list.append(color)
print(new_list)
['Red', 'Green', 'Blue']
Most list copy methods create a shallow copy. This means the list structure is copied but nested objects inside the list may still reference the same data.
For most beginner programs, shallow copying is sufficient.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net