Menu

You copied the list, but the original changed too. Shallow and deep copy in Python
📰

You copied the list, but the original changed too. Shallow and deep copy in Python

DEV Community: beginners·TalentOp Systems LLC·3 days ago
#B9FiFAjk
#devtobeginners#devto#dev#copy#list
Reading 0:00
15s threshold

Checked against official sources on November 15, 2026

You make a copy of a list. You change the copy. Then you look at the first list, and it changed too.

Nothing is broken. Python did what it was told. The copy was only one level deep.

Everything below was run in Python 3.13.5.

The bug in six lines

a = [ [ 1 , 2 ] , [ 3 , 4 ] ] b = a . copy ( ) b [ 0 ] . append ( 99 ) print ( a )

Enter fullscreen mode

Exit fullscreen mode

It prints:

[ [ 1 , 2 , 99 ] , [ 3 , 4 ] ]

Enter fullscreen mode

Exit fullscreen mode

We changed b , and a shows the new number. Why?

What a shallow copy really does

a.copy() makes a new outer list. But the inner lists are not copied. The new list just points to the same inner lists.

We can check it:

print ( a [ 0 ] is b [ 0 ] )

Enter fullscreen mode

Exit fullscreen mode

That prints True . Both names point to the same inner list. So an edit through one name shows up in the other.

The Python docs call this a shallow copy.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.