Python
Python syntax, built-ins, data structures
Python is a high-level, dynamically-typed programming language known for its readable syntax and versatility. In technical assessments, Python questions test understanding of core data types (lists, dictionaries, sets, tuples), comprehensions, lambda functions, decorators, memory management, and common gotchas like mutable default arguments and variable scoping. Mastery of Python's built-in functions and standard library is essential for solving coding problems efficiently.
Key formulas and rules
Key concepts
Mutable vs Immutable Types
Mutable objects (lists, dictionaries, sets) can be modified after creation. Immutable objects (int, float, string, tuple, frozenset) cannot be changed once created. Operations on immutables create new objects. This distinction is crucial for understanding how Python handles assignment, function arguments, and default values. For example, `a = [1, 2]; b = a; b.append(3)` modifies both a and b, but `a = (1, 2); b = a; b += (3,)` creates a new tuple for b while a remains unchanged.
List Operations and Methods
Lists support indexing, slicing (negative step reverses), concatenation (+), repetition (*), and membership testing (in). Key methods: append(x) adds one element, extend(iterable) adds multiple, insert(i, x) inserts at index, remove(x) removes first occurrence of value, pop([i]) removes and returns element at index (default last), sort() sorts in place (key parameter for custom sorting), reverse() reverses in place. Slicing creates shallow copies: `lst[:]` or `lst.copy()` duplicates the list.
Dictionary Operations
Dictionaries store key-value pairs with O(1) average lookup. Keys must be hashable (immutable). Access: d[key] raises KeyError if missing; use d.get(key, default) for safe access. Methods: keys(), values(), items() return view objects. setdefault(key, default) sets value if key missing. pop(key, default) removes and returns. update() merges dictionaries. dict comprehension: {k: v for k, v in pairs}. Since Python 3.7+, dicts maintain insertion order.
Set Operations
Sets are unordered collections of unique, hashable elements. Creation: {1, 2, 3} or set(iterable). Methods: add(x), remove(x) (raises KeyError if missing), discard(x) (no error), pop() removes arbitrary element. Set algebra: union (| or union()), intersection (& or intersection()), difference (- or difference()), symmetric difference (^ or symmetric_difference()). Subset/superset tests: issubset(), issuperset(), isdisjoint(). Sets are ideal for membership testing and removing duplicates.
Comprehensions
Comprehensions provide concise syntax for creating collections. List: [x*2 for x in range(5)] produces [0, 2, 4, 6, 8]. Dict: {x: x*x for x in range(5)}. Set: {x for x in iterable if x > 0}. Nested comprehensions: [[i*j for j in range(3)] for i in range(3)]. Generator expression: (x*2 for x in range(5)) — lazy evaluation, memory efficient. Comprehensions are generally faster than equivalent for-loops.
Lambda Functions and Higher-Order Functions
Lambda creates anonymous functions: lambda args: expression. Limited to single expression, no statements. Common use with map(), filter(), sorted(): `sorted(lst, key=lambda x: x[1])` sorts by second element. Map applies function: `map(lambda x: x*2, [1, 2, 3])` returns iterator yielding [2, 4, 6]. Filter selects elements: `filter(lambda x: x > 0, [-1, 1, -2, 2])` yields [1, 2]. Reduce (from functools) aggregates: `reduce(lambda a, b: a+b, [1, 2, 3, 4])` returns 10.
Worked examples
Example 1
What is the output of:
```
a = [1, 2, 3]
b = a
a = a + [4]
print(b)
```
Output: [1, 2, 3]
Step 1: `a` and `b` reference the same list [1, 2, 3].
Step 2: `a = a + [4]` creates a NEW list [1, 2, 3, 4] and rebinds `a` to it.
Step 3: `b` still references the original list [1, 2, 3].
Step 4: Therefore, `b` remains [1, 2, 3].
Note: If the code were `a += [4]` (in-place extension), both would show [1, 2, 3, 4].
Example 2
What is the output of:
```
def f(x, lst=[]):
lst.append(x)
return lst
print(f(1))
print(f(2))
```
Output:
[1]
[1, 2]
Step 1: Default argument `lst=[]` is evaluated ONCE when function is defined, not each call.
Step 2: First call `f(1)` uses the default list, appends 1, returns [1].
Step 3: The list [1] persists as the default.
Step 4: Second call `f(2)` uses the same list, appends 2, returns [1, 2].
Fix: Use `lst=None` as default, then `if lst is None: lst = []` inside function.
Example 3
What is the output of:
```
x = [i for i in range(3)]
y = [i for i in range(3) if i > 0]
z = list(filter(lambda i: i > 0, range(3)))
print(x, y, z)
```
Output: [0, 1, 2] [1, 2] [1, 2]
Step 1: List comprehension `x` includes all values from range(3): [0, 1, 2].
Step 2: List comprehension `y` filters with condition `i > 0`, keeping only 1 and 2: [1, 2].
Step 3: `filter(lambda i: i > 0, range(3))` applies the lambda to each element, keeping those where it returns True.
Step 4: Lambda returns True for 1 and 2, False for 0.
Step 5: `list()` converts filter object to list [1, 2].
Step 6: Final output shows x, y, and z as shown.
Example 4
What is the output of:
```
d = {'a': 1, 'b': 2}
print(d.get('c', 3))
print(d.setdefault('c', 4))
print(d)
```
Output:
3
4
{'a': 1, 'b': 2, 'c': 4}
Step 1: `d.get('c', 3)` returns default value 3 because key 'c' doesn't exist. Dictionary unchanged.
Step 2: `d.setdefault('c', 4)` checks if 'c' exists. It doesn't, so sets d['c'] = 4 and returns 4.
Step 3: Now 'c' exists in dictionary with value 4.
Step 4: Final dictionary contains all three keys.
Note: `get()` never modifies the dict; `setdefault()` may modify it.
Representative solved questions
See the kind of question in this topic before opening the full practice set.
Question 1
What is the output of:
x = [1, 2, 3, 4, 5]
print(x[::-1])
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[4, 3, 2]
Error
Answer: B. [5, 4, 3, 2, 1]
ExplanationStep 1: The slice notation [::-1] means start from end to beginning with step -1.
Step 2: This reverses the list.
Step 3: The original list [1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1].
Answer: [5, 4, 3, 2, 1]
Sources and review notes
This is an AISEA-authored practice question.
Review status: accepted · Reviewed 2026-08-13 · structure and answer-key checks, editorial quality checks, duplicate screening
Question 2
What is the output of:
def func(a, b=[]):
b.append(a)
return b
print(func(1))
print(func(2))
[1]\n[2]
[1]\n[1, 2]
[1]\n[2, 1]
Error
Answer: B. [1]\n[1, 2]
ExplanationStep 1: Default argument b=[] is evaluated once when function is defined, not each call.
Step 2: First call: func(1) appends 1 to b, returns [1].
Step 3: Second call: func(2) uses the same list object, appends 2, returns [1, 2].
Step 4: This is a common Python gotcha with mutable default arguments.
Answer: [1] followed by [1, 2]
Sources and review notes
This is an AISEA-authored practice question.
Review status: accepted · Reviewed 2026-08-13 · structure and answer-key checks, editorial quality checks, duplicate screening
Question 3
What is the output of:
x = 5
print(type(x) is int)
True
False
<class 'int'>
Error
Answer: A. True
ExplanationStep 1: type(x) returns the type of x, which is <class 'int'>.
Step 2: The 'is' operator checks identity (same object in memory).
Step 3: type(5) is int compares the type object of 5 with the int type object.
Step 4: They are the same object, so it returns True.
Answer: True
Sources and review notes
Common mistakes and useful habits
- Remember that `is` checks object identity while `==` checks value equality. Use `is` only for None checks and singleton comparisons.
- Avoid mutable default arguments in function definitions. Use `None` as default and initialize inside the function.
- Use list/dict comprehensions over map/filter with lambdas for better readability and often better performance.
- When iterating over a dictionary, use `.items()` to get both key and value: `for k, v in d.items()`.
- For efficient membership testing (checking if item exists), use sets instead of lists — O(1) vs O(n).
- Remember that strings and tuples are immutable — methods that appear to modify them actually return new objects.
- Use `enumerate()` when you need both index and value while looping: `for i, val in enumerate(lst)`.
Ready to test your understanding?
Work through 96 questions with explanations after each answer.