Skip to content

Interview PrepFoundations · Basics

Python Basics ​

Every output on these pages was produced by running the code on CPython 3.14.

1. What is Python, and how does Python code run? ​

The short answer

Python is a high-level, dynamically typed, garbage-collected language that favours readability. The usual implementation, CPython, first compiles your source into bytecode, simple instructions for a virtual machine, cached in __pycache__ as .pyc files, and then an interpreter loop executes that bytecode one instruction at a time. There is no separate build step you run yourself. Recent versions add speed-ups: a specialising interpreter since 3.11, and an experimental JIT compiler that turns hot bytecode into machine code, much improved in 3.15. Other implementations exist, such as PyPy, which has a mature JIT.

See the bytecode for one line:

python
import dis
dis.dis('total = price * qty')
text
  1           LOAD_NAME                0 (price)
              LOAD_NAME                1 (qty)
              BINARY_OP                5 (*)
              STORE_NAME               2 (total)
              LOAD_CONST               0 (None)
              RETURN_VALUE

Reading it: load price, load qty, multiply the top two values, store the result as total. Every Python line becomes a few of these small instructions, and the interpreter runs them in a loop.

ImplementationWhat it isUse
CPythonThe reference implementation, written in CAlmost everything
PyPyPython with a just-in-time compilerLong-running pure-Python code
MicroPythonA small Python for microcontrollersEmbedded devices

2. What does it mean that Python is dynamically and strongly typed? ​

The short answer

Dynamically typed means a variable has no fixed type; the value carries its type, and checks happen when the code runs. The same name can hold an int now and a str later. Strongly typed means Python does not silently convert between unrelated types: "3" + 4 raises a TypeError instead of guessing, unlike JavaScript, which gives "34". Type hints, such as def total(qty: int) -> int, add optional static checking with tools like mypy or Pyright, but Python itself does not enforce them at runtime.

python
order_id = 42          # an int
order_id = "ord_42"    # now a str; allowed: names are not typed

"3" + 4                # TypeError: can only concatenate str (not "int") to str
"3" + str(4)           # '34', you convert explicitly
PythonJavaScript
Static or dynamicDynamicDynamic
"3" + 4TypeError"34"
"3" * 2'33', defined repetition6, converts to number
Optional static typesType hints plus mypy or PyrightTypeScript

3. What is the difference between mutable and immutable objects? ​

The short answer

A mutable object can be changed in place after it is created: list, dict, set, bytearray, and most user-defined objects. An immutable object cannot: int, float, str, tuple, frozenset, bytes, and, since 3.15, frozendict. "Changing" an immutable value really creates a new object. This matters because variables are names bound to objects: two names can refer to the same mutable object, so a change through one is visible through the other. Only immutable, hashable objects can be dict keys or set members.

python
cart = ["shoes"]
saved = cart              # (1) both names point to the same list
cart.append("socks")      # (2) change the list in place
print(saved)              # ['shoes', 'socks']

code = "sale"
alias = code
code += "10"              # (3) builds a new string, rebinds `code`
print(alias)              # 'sale'
  1. No copy is made. Assignment binds another name to the same object.
  2. The list itself changes, so saved sees it.
  3. Strings cannot change, so += creates a new string and binds code to it. alias still points to the old one.
MutableImmutable
list, dict, set, bytearrayint, float, bool, str, bytes
Most class instancestuple, frozenset, frozendict (3.15+)
Cannot be dict keysCan be dict keys, if everything inside is hashable too

4. What are the differences between lists, tuples, sets, and dictionaries? ​

The short answer

A list is an ordered, mutable sequence, ["a", "b"], good for collections you add to and index by position. A tuple is an ordered, immutable sequence, ("GBP", 850), good for fixed records and dict keys. A set is an unordered collection of unique hashable items, {"a", "b"}, with very fast membership tests. A dict maps unique hashable keys to values, {"sku": 9, "qty": 2}, keeps insertion order since Python 3.7, and has very fast lookup by key. Sets and dicts are hash tables, so in is about constant time; on a list it scans every item.

listtuplesetdict
Literal[1, 2](1, 2){1, 2}{"a": 1}
OrderedYesYesNoYes, insertion order
MutableYesNoYesYes
DuplicatesAllowedAllowedNoKeys unique
x in cO(n) scanO(n) scanO(1) averageO(1) average, by key
Typical useA cart's itemsA coordinate, a keySeen IDs, deduplicationLookup by ID
python
skus = [9, 4, 9, 7]
unique = set(skus)                         # {9, 4, 7}
prices = {9: 2500, 4: 1200, 7: 800}        # dict: sku → pence
total = sum(prices[s] for s in skus)       # 7000
point = (51.5, -0.12)                      # tuple as a fixed pair

Why in on a set is fast. The set hashes the item to find its slot directly, instead of comparing against every element. Checking whether one of 1 million IDs has been seen takes microseconds with a set and milliseconds with a list.

Tuples are a bit smaller. On 64-bit CPython 3.14, sys.getsizeof([1, 2, 3]) is 88 bytes and sys.getsizeof((1, 2, 3)) is 72, because a list keeps spare room to grow.

5. What is the difference between is and ==? ​

The short answer

== checks equality: do the two objects have the same value, by calling __eq__. is checks identity: are they the same object in memory. Two separate lists with the same items are == but not is. Use is only for singletons, above all x is None; use == for values. CPython caches small integers from -5 to 256 and some strings, so is sometimes appears to work for values by accident, which is exactly why you must not rely on it.

python
a = [1, 2, 3]
b = a
c = list(a)
print(a == c, a is c, a is b)        # True False True

x = 256; y = int("256")
print(x is y)                        # True: small ints are cached
print(int("257") is int("257"))      # False: two separate objects

Reading it: c is a new list with equal contents, so == is true and is is false. b is another name for a itself, so is is true. The integer results show why is gives misleading answers for numbers.

6. What is the difference between a shallow copy and a deep copy? ​

The short answer

A shallow copy makes a new outer container but shares the inner objects: list(x), x.copy(), x[:], dict(x) and copy.copy(x). Changing a nested item through the copy changes the original. A deep copy, copy.deepcopy(x), recursively copies everything, so the result is fully independent. Plain assignment, y = x, copies nothing at all. Use deep copies sparingly: they are slower and duplicate memory; for flat lists of immutable values, a shallow copy is enough.

python
import copy

nested = [[1, 2], [3, 4]]
shallow = copy.copy(nested)
deep = copy.deepcopy(nested)
nested[0].append(99)

print(shallow)   # [[1, 2, 99], [3, 4]]  inner list is shared
print(deep)      # [[1, 2], [3, 4]]      fully independent
OperationNew outer objectNew inner objects
y = xNoNo
x.copy(), list(x), x[:], copy.copy(x)YesNo
copy.deepcopy(x)YesYes

7. What are list, dict and set comprehensions? ​

The short answer

A comprehension builds a collection from an iterable in one expression: [f(x) for x in items if cond(x)] for a list, {k: v for …} for a dict, {x for …} for a set. It is shorter and usually faster than a loop with .append. A generator expression, written with round brackets, (f(x) for x in items), produces values lazily, one at a time, without building a list in memory. Keep comprehensions simple: if one needs two conditions and nested loops, a normal loop is clearer.

python
orders = [{"id": 1, "total": 4000, "paid": True},
          {"id": 2, "total": 2550, "paid": False},
          {"id": 3, "total": 9000, "paid": True}]

paid_ids = [o["id"] for o in orders if o["paid"]]          # [1, 3]
by_id = {o["id"]: o["total"] for o in orders}              # {1: 4000, 2: 2550, 3: 9000}
amounts = {o["total"] // 1000 for o in orders}             # {9, 2, 4}
revenue = sum(o["total"] for o in orders if o["paid"])     # 13000, no list built

Memory, measured: sys.getsizeof of a list of 1 million squares is about 8.4 MB, while the equivalent generator expression object is about 200 bytes, because it produces each value only when asked (generators).

8. How does slicing work in Python? ​

The short answer

seq[start:stop:step] returns a new sequence from index start up to but not including stop, taking every stepth item. Any part can be left out: [:3] is the first three, [3:] is from the fourth on, [:] is a shallow copy. Negative indexes count from the end, so [-1] is the last item and [-3:] the last three. A negative step goes backwards, so [::-1] reverses. Slicing never raises an IndexError for out-of-range bounds; it just returns what exists.

python
word = "checkout"
print(word[1:4])     # 'hec'      indexes 1, 2, 3
print(word[-3:])     # 'out'      last three
print(word[::-1])    # 'tuokcehc' reversed
print([0, 1, 2, 3, 4, 5][::2])   # [0, 2, 4]
print(word[100:])    # ''         no error

Why stop is excluded: len(word[a:b]) is simply b - a, and word[:k] + word[k:] always gives back the whole string.

9. What is truthiness in Python, and how should you check for None? ​

The short answer

In a condition, every object counts as true or false. False values are False, None, zero of any number type, and empty collections and strings: "", [], {}, set(). Everything else is true, including [0] and "0". So if items: means "if the list is not empty". Check for None with is None, not with if not x, because 0 and "" are falsy too, and a valid quantity of 0 would be treated as missing.

python
print([bool(v) for v in [0, "", [], {}, None, 0.0, "a", [0]]])
# [False, False, False, False, False, False, True, True]

def apply_discount(price: int, percent: int | None) -> int:
    if percent is None:              # (1) correct: only "missing" is skipped
        return price
    return price * (100 - percent) // 100

apply_discount(1000, 0)              # 1000, a 0% discount, handled correctly
  1. if not percent: would be a bug: a real value of 0 would be treated as "no discount given". Here the result is the same, but for a quantity or a balance it would not be.

10. How do strings and f-strings work, and why should you use join to build strings? ​

The short answer

Strings are immutable sequences of Unicode characters. f-strings, f"Total: {total:.2f}", insert expressions directly and support format specifications such as decimals, padding and thousands separators; f"{value=}" prints the expression and its value, which is handy for debugging. Because strings cannot change, building one with += in a loop can copy the whole string each time, so use "".join(parts), which computes the final size once. Python 3.14 adds t-strings, t"…", which produce a template object instead of a string, so libraries can safely escape the values, for example in SQL or HTML.

python
total = 1234.5
qty = 3
print(f"Total: £{total:,.2f}")       # Total: £1,234.50
print(f"{qty=}")                     # qty=3
print(f"{'id':<6}|{'qty':>5}")       # id    |  qty

lines = [f"{sku},{n}" for sku, n in [("A1", 2), ("B7", 1)]]
csv = "\n".join(lines)               # one allocation for the result

Strings, bytes and encoding. str is text; bytes is raw data. Convert with text.encode("utf-8") and data.decode("utf-8"). Since Python 3.15, UTF-8 is the default encoding for open() and other text I/O on every platform, which removes a classic Windows bug where files were read with a legacy encoding.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Python
Foundations
Functions
Iteration
Objects
Internals
Errors and packaging
Concurrency
Modern Python
Coding
Other topics
Nothing picked yet