Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.1 — Interview Deep Dive: Core Language Questions
Python · Example 2 of 2

Defaults, scope and truthiness

The comprehension variable n does not leak out. In Python 2 it did.

The core-language questions that come up in almost every Python interview: mutability, is versus ==, default arguments, scope, copying, comprehensions and truthiness. For each one you get the precise answer and a program that proves it.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Predict the output, then run it: a = [1, 2]; b = a; b += [3]; c = a; c = c + [4]; print(a, b, c). Explain why += and + behave differently on lists.

02

Write unique_in_order(items) that returns the items with duplicates removed, keeping first-seen order, without using a default mutable argument.

03

Write a function make_counter() that returns a function; each call to the returned function gives 1, 2, 3, and so on, with no global variable.

Explain it without notes

01

What is the difference between is and ==? When is is the right operator?

02

Why is def f(x, items=[]) a bug, and what is the standard fix? When is a mutable default actually useful?

03

Explain shallow copy versus deep copy with an example where the difference changes the result.

04

Why does counter += 1 raise UnboundLocalError inside a function when counter exists at module level?

05

Python is sometimes called pass-by-value and sometimes pass-by-reference. What is the accurate description?

06

Why can a tuple be a dict key when a list cannot? Is every tuple usable as a key?

07

Is Python a compiled or an interpreted language?

Defaults, scope and truthiness
Sign in to run this example in your browser.

Expected output

[1, 2] [1, 2]
stored default: ([1, 2],)
[1] [2]
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
nonlocal counter: 2
[False, False, False, False, False, False, True, True, True]
[0, 1, 4]
NameError: name 'n' is not defined