Skip to content

Module 17 · Advanced Python Concepts — topic 3 of 14

Shallow copy

Making new containers that share their contents: slicing, list(), .copy(), dict.copy(), copy.copy for any object, and why nested objects are still shared after a shallow copy.

Beginner 8 min read·Lesson 249 of 306 in Python Programming

Learning objectives

  • Create shallow copies of lists, dicts, sets and objects
  • Predict which changes affect the original
  • Decide when a shallow copy is enough

Definition

A shallow copy creates a new outer container whose elements are references to the same objects as the original. The container itself is independent, but any mutable objects inside it are shared.

Introduction

Copying a list of numbers is easy and safe. Copying a list of lists is where surprises start — the outer list is new, but the inner lists are not.

Why it matters

Shallow copies are fast and usually enough. Knowing exactly what they share lets you use them confidently and recognise when you need a deep copy instead.

Detailed explanation

Ways to shallow-copy: lst[:], list(lst), lst.copy(), dict(d), d.copy(), {**d}, set(s), s.copy() and copy.copy(obj) for any object.

Adding, removing or replacing items in the copy doesn't affect the original — the containers are separate.

Mutating a shared inner object (appending to a nested list, changing a nested dict) is visible through both copies.

For containers of immutable values (numbers, strings, tuples of immutables), a shallow copy behaves like a full copy.

copy.copy on a custom object creates a new instance whose attributes refer to the same values; a list attribute is shared.

Classes can customise copying by defining __copy__.

Shallow copies are cheap: they copy only references, not the objects themselves, so they are a good default for flat data.

Syntax

Python
import copy
new_list = old_list.copy() # or old_list[:] / list(old_list)
new_dict = old_dict.copy() # or {**old_dict}
new_obj = copy.copy(obj)
  • New outer container.
  • Inner objects are shared.
  • Fine for flat, immutable contents.

Code examples

Copying a flat list

Python
import copy
orig = [1, 2, 3]
c1 = orig[:]
c2 = list(orig)
c3 = copy.copy(orig)
c3.append(4)
print(orig, c3, c1 is orig)
Output
[1, 2, 3] [1, 2, 3, 4] False

Nested lists are shared

Python
orig = [[1, 2], [3, 4]]
shallow = orig.copy()
shallow[0].append(99)
shallow.append([5])
print(orig)
print(shallow)
print(orig[0] is shallow[0])
Output
[[1, 2, 99], [3, 4]]
[[1, 2, 99], [3, 4], [5]]
True

More examples

Dictionaries and objects

Python
import copy
settings = {"theme": "dark", "plugins": ["git", "lint"]}
user = settings.copy()
user["theme"] = "light"
user["plugins"].append("spell")
print(settings)
print(user)
class Config:
def __init__(self):
self.values = {"debug": False}
a = Config()
b = copy.copy(a)
b.values["debug"] = True
print(a.values, a is b, a.values is b.values)
Output
{'theme': 'dark', 'plugins': ['git', 'lint', 'spell']}
{'theme': 'light', 'plugins': ['git', 'lint', 'spell']}
{'debug': True} False True

Step-by-step explanation

  • Replacing theme in the copy doesn't touch the original, because each dict has its own key slots.
  • The plugins list is shared, so appending through the copy changes the original too.
  • copy.copy makes a new Config object, but its values dictionary is the same object.

Expected output

Running “Dictionaries and objects” prints exactly:

TextOutput
{'theme': 'dark', 'plugins': ['git', 'lint', 'spell']}
{'theme': 'light', 'plugins': ['git', 'lint', 'spell']}
{'debug': True} False True

Practical applications

  • Copying a list before sorting or filtering it.
  • Creating a modified version of a flat settings dictionary.

Best practices

  • Use shallow copies for flat data.
  • Prefer .copy() or list() for readability.
  • Use deepcopy when nested data will be modified.

Common mistakes

Shallow copy of nested settings

Avoid

user = defaults.copy()
user["colors"]["bg"] = "black" # changes defaults

Prefer

import copy
user = copy.deepcopy(defaults)

Nested dictionaries are shared by a shallow copy.

Important notes

  • Building a new structure with a comprehension is often clearer than copying and then modifying.

Key takeaways

  • Shallow copies duplicate the container, not its contents.
  • Nested mutable objects remain shared.
  • copy.copy works for any object.

Try it yourself

  1. 1
    Show with is checks which parts of a list of dictionaries are shared after .copy().
  2. 2
    Copy a dict of lists so the lists are independent, without using deepcopy.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic