• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

The Coding Couple

Pair programming is a lifetime commitment.

  • Home
  • Categories
    • Arduino
    • JavaScript
    • Python
    • Raspberry Pi
  • About Us
    • Privacy Policy
  • Contact

Avoid using mutable values as default parameter values in Python (Today I Learned)

April 28, 2017 by Ashley

Today I learned something interesting about the way Python functions behave with default parameter values: avoid using mutable objects such as lists as default values for function parameters.

Why? | Source

Why? | Source

What’s the problem?

Default parameter values are evaluated when function is evaluated.  Which means default parameter values are only evaluated once.  If you use a mutable value type as a default parameter value you will find the default parameter value will not reset each time you call the function.  Take a look at the example below:


def favorite_toppings(name, toppings=[]):
    toppings.append("pepperoni")
    return print("{0}'s favorite toppings are {1}".format(name, ', '.join(toppings)))

If you call favorite_toppings several times without passing in an argument for toppings you get the following output:

>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni
>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni, pepperoni
>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni, pepperoni, pepperoni

A workaround

The state of toppings does not reset to an empty list with each sequential call to favorite_toppings. To avoid this problem refactor the method setting None as the default type and check to see if an argument has been passed in.  Take a look at the revised code below:

def favorite_toppings(name, toppings=None):
    if toppings is None:
        toppings = []
    toppings.append("pepperoni")
    return print("{0}'s favorite toppings are {1}".format(name, ', '.join(toppings)))

If you call favorite_toppings three more times with the revised method the output is:

>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni
>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni
>>> favorite_toppings("Ashley")
Ashley's favorite toppings are pepperoni

So remember

Always use immutatable objects such as strings and integers for default parameter values.  For more details on functions definitions in Python, read the docs here.

Fortunately, this is not a lesson I had to learn the hard way, but rather something I had either missed when I first learned how to program in Python or forgot it was something I should avoid in the years since learning Python.  A quick language comparison: in C# you will get compile errors if you try to use an mutable value as a default parameter value.

Related Posts

  • Fractions in Python | Today I LearnedFractions in Python | Today I Learned
  • .mjs extension (A JavaScript module file) | Today I Learned.mjs extension (A JavaScript module file) | Today I Learned
  • How to watermark images with Python and Pillow (PIL)How to watermark images with Python and Pillow (PIL)
  • There’s a name for that:  the Kebab CaseThere’s a name for that: the Kebab Case
  • Tinkering Around with Adafruit’s PyBadge LCTinkering Around with Adafruit’s PyBadge LC
  • Using WSL on Corporate VPNUsing WSL on Corporate VPN

Filed Under: Python, Today I Learned Tagged With: default value, functions, optional parameters, python, TIL, today I learned

Previous Post: « Adafruit Joy Bonnet for the Raspberry Pi
Next Post: NESPi Raspberry Pi Case (RetroFlag) Mini Review »

Primary Sidebar

Social Media

  • GitHub
  • Instagram
  • Twitter
  • YouTube

Recent Posts

  • Pokémon Color Picker | A web app built with HTML/CSS + JavaScript
  • Pokéball Single DIV CSS Drawing | Tutorial
  • Error: [🍍]: “getActivePinia()” was called but there was no active Pinia
  • Trijam #261 Game Jam Diary: One Wrong Move
  • Using WSL on Corporate VPN

Recent Comments

  • Lizzy on Creation Crate Month 2: An Arduino Powered Memory Game
  • Ashley Grenon on Creation Crate Month 2: An Arduino Powered Memory Game
  • Lizzy on Creation Crate Month 2: An Arduino Powered Memory Game
  • kelly on Creation Crate Month 2: An Arduino Powered Memory Game
  • Ashley on Creation Crate Month 3: An Arduino Powered Distance Detector

Follow us on Instagram!

This error message is only visible to WordPress admins

Error: No feed found.

Please go to the Instagram Feed settings page to create a feed.

Categories

  • Arduino
  • Conferences
  • Debugging
  • Game Jams
  • HTML and CSS
  • JavaScript
  • Programming Languages
  • Python
  • Raspberry Pi
  • Today I Learned

Archives

  • May 2024
  • April 2024
  • March 2024
  • May 2022
  • December 2021
  • May 2021
  • March 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • June 2019
  • April 2019
  • September 2017
  • April 2017
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • April 2015
  • January 2015

Tags

adafruit arduino brackets c# code smell codestock coding standards conventions creation crate debugging developer devspace electronics es6 es2015 game development game jam gotcha hackathon hoisting html html5 javascript led naming conventions nintendo phaser pluralsight pokemon programmer python raspberry pi retro retropie scope self improvement single div single div drawing subscription box TIL today I learned troubleshooting vue vuejs windbg

Footer

About Us

We are the Coding Couple.  Two people who met in college and decided they wanted to pair program for the rest of their ...

Read More »

Most Recent Posts

Pokémon Color Picker | A web app built with HTML/CSS + JavaScript

Pokéball Single DIV CSS Drawing | Tutorial

Error: [🍍]: “getActivePinia()” was called but there was no active Pinia

Trijam #261 Game Jam Diary: One Wrong Move

Social Media

  • GitHub
  • Instagram
  • Twitter
  • YouTube

Copyright Notice

© The Coding Couple, 2015 – 2023. Excerpts and links may be used, provided that full and clear credit is given to The Coding Couple with appropriate and specific direction to the original content.

Copyright © 2025 · Foodie Pro Theme by Shay Bocks · Built on the Genesis Framework · Powered by WordPress