Python MCQs with answers for placement preparation
Review Python types, collections, control flow and functions with explained questions. Use concept practice for technical placements and selected GATE DA programming foundations, alongside writing and testing code.
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
8 rulesSequence Slicing: seq[start:stop:step] extracts indices from start up to stop - 1 with step size step; negative index maps to
String Reversal: s[::-1] reverses string s in time and auxiliary space
List Comprehension: [expr for x in iterable if cond] maps and filters elements into a newly allocated list
Dict Comprehension: {k: v for item in iterable if cond} builds key-value dictionary mappings compactly
Lambda Expression: lambda x, y: x + y creates an anonymous in-line callable function
Half-Open Range: range(start, stop, step) generates integers in interval incrementing by step
Set Algebraic Operations: s1 | s2 (union ), s1 & s2 (intersection ), s1 - s2 (difference ), s1 ^ s2 (symmetric difference)
Index Enumeration: enumerate(iterable, start=0) yields 2-tuples of (index, item) starting from start
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: [x2 for x in range(5)] produces [0, 2, 4, 6, 8]. Dict: {x: xx for x in range(5)}. Set: {x for x in iterable if x > 0}. Nested comprehensions: [[ij for j in range(3)] for i in range(3)]. Generator expression: (x2 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.
Variable Scope and Closures
Python has LEGB scope resolution: Local, Enclosing, Global, Built-in. global keyword declares global variable; nonlocal refers to nearest enclosing non-global scope. Default arguments are evaluated once at definition time — mutable defaults cause bugs: def f(lst=[]): lst.append(1) accumulates across calls. Closures remember enclosing scope: functions returning functions capture variables from outer scope. Late binding closures capture variable names, not values — use default arguments to bind values immediately.
Common Python Gotchas
1) is vs ==: is checks identity (same object), == checks equality. None is None is correct, never use == None. 2) Chained comparisons: 1 < x < 10 is valid Python, equivalent to 1 < x and x < 10. 3) Boolean values: 0, '', [], {}, None are falsy; everything else is truthy. 4) Integer caching: -5 to 256 are pre-allocated; is may work for equality accidentally. 5) Shallow vs deep copy: copy.copy() shallow copies, copy.deepcopy() recursively copies nested structures. 6) Modifying iterable while iterating causes unexpected behavior — iterate over a copy instead.
Worked examples
Example 1
What is the output of:
a = [1, 2, 3]
b = a
a = a + [4]
print(b)Solution
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))Solution
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)Solution
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)Solution
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:
print(2 ** 3 ** 2)
Answer: B. 512
ExplanationStep 1: ** has right-to-left associativity.
Step 2: 3 ** is evaluated first.
Step 3: Then 2 ** .
Answer: 512
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:
print(min([3, 1, 4, 1, 5], key=lambda x: -x))
Answer: B. 5
ExplanationStep 1: key=lambda x: -x transforms each element to its negative.
Step 2: The transformed values are -3, -1, -4, -1, -5.
Step 3: min() finds the smallest transformed value (-5), which came from 5.
Answer: 5
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:
print(hash('abc') == hash('abc'))
Answer: A. True
ExplanationStep 1: hash() returns the hash value for a string.
Step 2: Same string produces same hash within a single Python run.
Step 3: hash('abc') == hash('abc') is True.
Answer: True
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
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.