Practice mode Python

What is the recommended way to give a function parameter a fresh empty list as its default on every call?

Correct answer D. Use items=None and create the list inside the function when items is None

Explanation

Default values are evaluated only once, when the function is defined, so items=[] or even items=[].copy() is shared across calls. The idiom is to default to None and then write if items is None: items = []. This creates a new list on every call that omits the argument.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.