Copying Lists
Writing b = a does not copy the list, it gives the same list a second name, so changing one changes the other. Use a.copy(), list(a) or a[:] for a shallow copy. Nested lists are still shared, so use copy.deepcopy for a fully independent copy.
Example
a = [1, 2, 3]
b = a
b.append(4)
print(a)
c = a.copy()
c.append(5)
print(a, c)
import copy
nested = [[1], [2]]
deep = copy.deepcopy(nested)
deep[0].append(9)
print(nested, deep)Result
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5] [[1], [2]] [[1, 9], [2]]
Exercise
Make a real copy.
b = a.()
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.