Python Practice › List Programs › Program 16
Copy a list
Write a Python program to copy a list so that changing the copy does not change the original.
Input
[1, 2, 3]
Output
[1, 2, 3] [1, 2, 3, 4] [1, 2, 3]
Approach
- Use
copy(),list()or slicing[:].
Solution
original = [1, 2, 3]copy1 = original.copy()copy2 = original[:]copy1.append(4)print(original, copy1, copy2)Output
[1, 2, 3] [1, 2, 3, 4] [1, 2, 3]
Line by line
Lines 2-3
Both create new lists.
Line 4
Changing the copy leaves the original alone.
Watch out
copy2 = original would not copy; both names would refer to the same list.
Learn the concept
New to this topic? Read the lesson, then come back.