Skip to content
Python Trap

Python Trap

Python List Copy Trap: Why b = a Doesn't Make a Copy

· Python list copy trap: b = a is not a copy | a ko kisne badla?

In Python, b = a doesn't copy a list. It gives the same list a second name, so b.append(4) changes a to [1, 2, 3, 4] too. Use a.copy() for a separate list. It is a shallow copy, so nested lists need copy.deepcopy.

The code

code
a = [1, 2, 3]
b = a
b.append(4)
print(a)
fix
b = a.copy()
Daily TrapOne more trap, every dayA short JavaScript or Python output puzzle each day. Guess, see why, keep your streak.