Menu

Sign in to track your progress and unlock all features.

Theme style

Start learning freeLog in

Problem No 16

Write a function that avoids mutable default args

Medium

≈ 13 minute session

Summary

Learn how to write functions that use immutable defaults to avoid shared mutable state between calls.

Problem statement

In Python, using a mutable object (like a list) as a default argument is a common pitfall because the same object is reused across calls. Your task is to implement append_to(element, lst=None) that appends element to lst and returns the list. If lst is not provided (None), create and use a new list for that call so calls don't share state.

Task

Implement a function that safely appends an element to a list without using a mutable default argument.

Examples

Basic usage

Input

append_to(1)

Output

[1]

Explanation

When called without a list, append_to should create a new list and return [1].

Input format

A function call append_to(element, lst=None). element may be any value; lst is optional.

Output format

Return the list after appending the element. The returned value will be shown as a Python list string representation.

Constraints

Do not use a mutable object as a default value. If lst is None, create a new list inside the function.

Samples

Sample input 0

append_to('a', ['b'])

Sample output 0

['b', 'a']

Explanation 0

When a list is provided, append the element to it and return the same list.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.