The Hidden Pitfalls of Mutables I Wish I Knew Earlier

Jenny Ouyang
9 min read1 day ago
AI Generated Image

If you don’t have a Medium subscription, you can still access the full article via my friend link.

Have you encountered situations where the values of a list or dictionary change unexpectedly? Often, we didn’t intend for these changes to happen, but the nature of mutables can catch us off guard. Even experienced developers occasionally find themselves dealing with tricky side effects when working with mutable objects.

In Python, mutables — such as lists, dictionaries, and sets — allow their content to be modified after creation. While this flexibility can be useful, there are certain scenarios where using mutable objects can lead to problems or unintended behavior.

After having these challenges many times in my own work, I was so motivated to gather some key scenarios where you should be cautious about relying on mutables. Here are the important cases to watch out for:

1. Default Argument Values in Functions

One of the most common pitfalls with mutable objects is using them as default argument values in function definitions. Since default argument values are only evaluated once (when the function is defined), mutating that default argument affects all future calls to the function.

Example:

--

--

Jenny Ouyang

A Parent | Writer | Software Engineer | PhD | Former Researcher passionate about exploring computer science, AI, housing, and the intricacies of human nature.