Programming Languages

Python Shallow Copy: A New List Can Still Share Nested Data

SoftwareJobs.io editorial1 December 20262 min read

Copying a list does not always make every object inside it independent. A shallow copy creates a new outer collection but keeps references to its contained objects. This can explain a change that appears in two places.

Try a nested-list example

original = [["A"], ["B"]]
copy_list = original.copy()
copy_list[0].append("X")
print(original)

The printed original is [['A', 'X'], ['B']]. The two outer lists are separate, but their first item refers to the same inner list. Python’s copy documentation explains this difference between copying a container and recursively copying its contents.

Compare replacing an item

Start again, then assign copy_list[0] = ["Z"]. This replaces an item in the copied outer list instead of changing the shared inner list. The original’s first inner list remains ["A"]. Predict the result before running both versions.

Choose ownership before a copying rule

A deep copy may help in some cases, but it can also copy more than intended and is not a universal solution for every object. Ask which data should be shared and which should be independent. An explicit small structure is easier to reason about than adding deep copying everywhere.

Practice checks

  • Change an inner object.
  • Replace an outer-list item.
  • Explain which reference is shared.

For Malta data and backend interviews, draw the outer lists and inner objects if that helps. A simple reference diagram often explains the behaviour more clearly than saying that a copy is “not working”.

Sources and further reading

Browse current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter