Retired

Mutable Python Defaults Issue (retired)

Description:

Description:

In this task, you need to implement a function add_task that adds a new task to a list of tasks. The function should accept a task and an optional list of tasks. If the list is not provided, the function should create a new list. The goal is to demonstrate why using mutable objects (like lists) as default arguments is a bad idea and how to fix it.

Initial Function Signature:

def add_task(task, task_list=[]) -> list:
    # Fix it

Example:

tasks = add_task("Buy milk")
print(tasks)  # Expected output: ['Buy milk']

tasks = add_task("Buy bread")
print(tasks)  # Expected output: ['Buy bread']

tasks = add_task("Buy eggs", [])
print(tasks)  # Expected output: ['Buy eggs']

Hint:

  • Avoid using mutable objects as default arguments to prevent unexpected behavior.
Debugging
Lists

Stats:

CreatedFeb 1, 2025
Warriors Trained18
Total Skips0
Total Code Submissions45
Total Times Completed16
Python Completions16
Total Stars1
% of votes with a positive feedback rating36% of 7
Total "Very Satisfied" Votes1
Total "Somewhat Satisfied" Votes3
Total "Not Satisfied" Votes3
Total Rank Assessments9
Average Assessed Rank
8 kyu
Highest Assessed Rank
7 kyu
Lowest Assessed Rank
8 kyu
Ad
Contributors
  • ANovelForStudy Avatar
Ad