Python Program to Copy a List
Beginner · Lists
Writing b = a does not copy a list: it gives the same list a second name, so a change through one name shows up through the other. This program shows that trap, then makes a shallow copy and a deep copy, and shows why a list that holds other lists needs a deep copy.
Program
original after alias.append(4): [1, 2, 3, 4] marks after shallow.append(): [[90, 85], [70, 65]] marks after shallow[0][0] = 0: [[0, 85], [70, 65]] marks after deep[0][0] = 0: [[90, 85], [70, 65]] deep: [[0, 85], [70, 65]]
How it works
alias = originalmakes no copy at all, so appending throughaliaschangesoriginaltoo.marks.copy()makes a shallow copy: a new outer list, so appending toshallowleavesmarksalone.- The inner lists are not copied, though.
shallow[0]andmarks[0]are the same list, so settingshallow[0][0] = 0changesmarksas well. This is the shallow copy trap. copy.deepcopy()copies the inner lists too, so changingdeepnever touchesmarks.- For a flat list of numbers or strings, a shallow copy is all you need; use a deep copy when the list holds other lists or dictionaries.
Other ways to write it
Three ways to make a shallow copy
numbers: [5, 10, 15] a: [5, 10, 15, 20] | b: [5, 10, 15] | c: [5, 10, 15] Is a the same list as numbers? False
copy(), list() and the full slice [:] all make a new list, and is confirms that a is a different object from numbers.
Copying each row of a list of lists
grid: [[1, 2], [3, 4]] grid_copy: [[1, 2], [3, 99]]
Copying every row by hand is enough for a list of lists one level deep; copy.deepcopy() handles any depth.
Try it yourself
Replace copy.deepcopy(marks) with marks[:] and see the shallow copy trap come back.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Remove an Element from a List
- Reverse a List
- Work with a Nested Dictionary
- Merge Two Lists
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises