Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Write a function that avoids mutable default args

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

Python practice13 minFunctions & ScopeIntermediateLast updated March 17, 2026

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]

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 1

Input

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

Output

['b', 'a']

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