In partnership with

Copying data structures in Python can be deceiving and tricky. You might try to copy a list into a new variable as such:

a = [1, 2, 3]
b = a

At the surface, you may think that a and b are 2 separate lists. But when you go to append to b:

b.append(4)

print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]

But you never appended to a! What’s going on here?

Assignments are not copies

Remember that the = operator is an assignment. It means that the variable b now points to the same object as a.

» Pointers is how the code is able to identify where something lives in memory.

So, when you do an assignment operation, you’re writing code to say “point to this specific object in memory”:

Creating a shallow copy

In order to avoid this, you’re going to want to use a Python built-in library: copy, which allows you to create copies in one line of code:

import copy

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

print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]

If we were to diagram it, it would look like this:

Perfect! This seems to work for a single-layered list. If we were to continue testing, what would happen if I have a nested list?

import copy

a = [[1, 2], [3, 4]]
b = copy.copy(a)

# append to the list and the first element
b.append([5, 6])
b[0].append(99)

print(a)  # [[1, 2, 99], [3, 4]]
print(b)  # [[1, 2, 99], [3, 4], [5, 6]]

Our initial solution of using copy does work, but not entirely. If you want a true clone that’s independent of your original variable, leverage deepcopy instead:

import copy

a = [[1, 2], [3, 4]]
b = copy.deepcopy(a) # <-- This changed to `deepcopy`

# append to the list and the first element
b.append([5, 6])
b[0].append(99)

print(a)  # [[1, 2], [3, 4]]
print(b)  # [[1, 2, 99], [3, 4], [5, 6]]

Do we need to deepcopy everything?

Thankfully, we don’t. There’s some criteria that should be met if you need to use deep copy. You’ll want to use deepcopy when:

  • Your object is nested (such as above)

  • The inner objects are mutable, such as lists, dicts, and sets.

You don’t need to deepcopy when:

  • The object is immutable (ints, floats, strings, tuples of immutables, frozensets)

  • The data structure has only one level (such as the example above).

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate

Keep Reading

No posts found