Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 6

Implement a function with a default argument

Easy

10 minute session

Summary

Practice using default arguments safely by creating a function that appends an item to a list, avoiding the common mutable-default pitfall.

Problem statement

Implement a function append_item(item, lst=None) that appends item to the list lst and returns the resulting list. If lst is omitted or None, the function should create and return a new list containing only item. Do not use a mutable object as a default argument (e.g., avoid lst=[] in the signature). The function must ensure separate calls with the default create distinct lists.

Task

Write append_item(item, lst=None) that appends item to lst. If lst is not provided, create a fresh list each call.

Examples

Default list creation

Input

append_item(1)

Output

[1]

Explanation

No list provided; a new list [1] is created and returned.

Input format

First argument: item to append. Second optional argument: list to append to (or None to use a new list).

Output format

The list after appending the item.

Constraints

Ensure that a new list is created when lst is None. Do not mutate a shared default list across calls.

Samples

Sample input 0

append_item('a', ['x'])

Sample output 0

['x', 'a']

Explanation 0

Appends 'a' to the provided list ['x'] and returns it.

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.

07:39 PM

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