Functions & Scope · Question 8 · Medium

The tag function uses a dictionary as a default parameter value. What do the three calls print?

def tag(key, seen={}):
    seen[key] = seen.get(key, 0) + 1
    return seen[key]

print(tag("a"), tag("b"), tag("a"))
  1. 1 1 1
  2. 1 2 3
  3. 1 1 2
  4. 1 2 2
Answer and explanation

Answer: C. 1 1 2

Explanation: The default dictionary is created once, when the function is defined, and is shared by every call. So the count for "a" survives from the first call and becomes 2 in the third call, while "b" is counted once.

Previous: A function is defined as def book(src, dst, seats=1). Which of these calls is… · Next: A function receives keyword arguments through **info. What does sorted(info)…

Practise functions & scope

Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.

More functions & scope questions

More python practice

Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge