The Mutable Default Argument Mess in Python

The Mutable Default Argument Mess in Python

Meet Kevin, ๐Ÿ™‹โ€โ™‚๏ธ Kevin is learning Python. One day he was given a problem to solve as follows:

Meet Kevin, ๐Ÿ™‹โ€โ™‚๏ธ Kevin is learning Python. One day he was given a problem to solve as follows:

Design a function that appends โ€˜#โ€™ to a list provided as an argument and then prints it. If no argument is provided then the function should use an empty list as a default.

Kevin quickly comes up with the following solution:

def append(l = []):
    l.append('#')
    print(l)

Looks good, time for testing the solution:

append([1, 2, 3])
## OUTPUT: [1, 2, 3, '#'] | OK

append()
## OUTPUT: ['#']    | OK
append()
## OUTPUT: ['#', '#']  | Strange!!
  • The first call to append worked fine. It added ## to the list [1, 2, 3] and then printed it.
  • The second also worked as expected. This time no list is provided as an argument, so it used the default empty list and appended a ## to it.
  • Now, the third call resulted in something unexpected.
  • When we once again called the append without argument, it printed ['#', '#'] instead of ['#'] as we got in the above call.

python programming mutability

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Guide to Python Programming Language

Guide to Python Programming Language

Python Programming: A Beginnerโ€™s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Pythonโ€™s a snake right? and Why is this programming language named after it?

Python Hello World Program - Create & Run Your First Python Program in PyCharm

Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.