Skip to content
Discussion options

You must be logged in to vote

a) Predicted output

[1, 2] [1, 2] [3]

b) Why the first two lists look identical

Two things combine here:

  1. The default value is created once, when def runs, not on each call. Python evaluates bucket=[] a single time, when the function is defined, and stores that one list object on the function. Every call that omits bucket reuses that same list.

  2. print evaluates all its arguments before printing anything. The calls happen in order:

    • add_item(1) appends 1 to the shared default list and returns that same list object (not a copy).
    • add_item(2) appends 2 to the same list and returns it again.
    • add_item(3, []) gets a brand new list, so it's unaffected: [3].

    Only after all three calls finish d…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Temple-Daemon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants