Skip to content

Python Practice (Interactive)

Intuition

Learning through practice: Practice problems are like training drills, they help you apply knowledge and identify areas that need more study.

Why it matters: Regular practice builds confidence and reveals patterns in how concepts are tested. Each problem reinforces key programming concepts.

The key insight: Making mistakes during practice is valuable, each error points to a concept that needs clarification.

Python, Interactive Practice

13 auto-graded practice problems covering core Python concepts. Select an answer, submit, and review the explanation.


Data Structures

Q1. What does list(map(lambda x: x**2, range(5))) return?

A. [1, 4, 9, 16, 25] B. [0, 1, 4, 9, 16] C. [0, 2, 4, 6, 8] D. [1, 2, 3, 4, 5]

Show answer, B

Answer: B, range(5) produces [0, 1, 2, 3, 4]. Mapping x² gives [0, 1, 4, 9, 16].”

Q2. What is the time complexity of checking membership (x in lst) in a Python list?

A. O(1) B. O(log n) C. O(n) D. O(n log n)

Show answer, C

Answer: C, Lists use a linear search for membership tests, which is O(n). For O(1) lookups, use a set or dict.”

Q3. What does \{'a': 1, 'b': 2\}.get('c', 3) return?

A. None B. KeyError C. 3 D. False

Show answer, C

Answer: C, dict.get(key, default) returns the default value (3) when the key (‘c’) is not found.”


Functions and Scope

Q4. What is printed by print([x for x in range(10) if x % 3 == 0])?

A. [3, 6, 9] B. [1, 2, 3, 4, 5, 6] C. [0, 3, 6, 9] D. [0, 1, 2, 3]

Show answer, C

Answer: C, The list comprehension filters for numbers divisible by 3: 0, 3, 6, 9.”

Q5. What does def f(a, b=[]): b.append(a); return b return when called as f(1); f(2)?

A. [1], [2] B. [1, 2] C. [1, 2], [1, 2] D. TypeError

Show answer, B

Answer: B, Mutable default arguments are shared across calls. After f(1), b = [1]. After f(2), b = [1, 2]. This is a common Python gotcha.”


Core Language Features

Q6. Which sorting algorithm does Python’s built-in sorted() use?

A. Quicksort B. Merge sort (Timsort) C. Heap sort D. Bubble sort

Show answer, B

Answer: B, Python uses Timsort, a hybrid of merge sort and insertion sort. It is stable and has O(n log n) worst-case time complexity.”

Q7. What is the result of type((1, 2, 3))?

A. ‘<class ‘list’>” B. <class ‘set’> C. <class ‘tuple’> D. “<class ‘dict’>”]} correctAnswer={2} explanation=“(1, 2, 3) with parentheses and commas is a tuple, not a list or set.”} difficulty=“easy” />

Show answer, C

Answer: C, (1, 2, 3) with parentheses and commas is a tuple, not a list or set.”

Q8. What does (yield from x for x in range(3)) do?

A. Returns [0, 1, 2] B. Raises SyntaxError C. Yields a single generator object D. Returns a generator that yields 0, 1, 2

Show answer, D

Answer: D, This is a generator expression. It returns a generator object that yields 0, 1, 2 when iterated.”


List Comprehensions

Q9. What is the output of [i * j for i in range(3) for j in range(3) if i != j]?

A. [2, 6] B. [0, 0, 2, 0, 6] C. [0, 2, 0, 6] D. IndexError

Show answer, B

Answer: B, The nested comprehension iterates all pairs (i,j) from 0-2, filters out i==j, and multiplies the remaining pairs: 01=0, 02=0, 10=0, 12=2, 20=0, 21=2. Result: [0, 0, 2, 0, 6].”


Generators

Q10. What is the key advantage of sum(i*i for i in range(10**9)) over sum([i*i for i in range(10**9)])?

A. Faster computation time B. Produces a more accurate result C. Uses less CPU time D. Constant memory usage vs. allocating a billion-element list

Show answer, D

Answer: D, The generator expression yields one value at a time (constant memory), while the list comprehension materializes all 10^9 values in memory before summing. The generator avoids a memory allocation of ~8 GB.”


Decorators

Q11. Given def timer(func): import time; def wrapper(*args, **kwargs): start=time.time(); result=func(*args, **kwargs); print(time.time()-start); return result; return wrapperwhat does @timer def compute(): pass do?

A. Computes only once and caches the result B. Raises a TypeError C. Replaces compute with wrapper, printing elapsed time on each call D. Makes compute asynchronous

Show answer, C

Answer: C, The @timer decorator replaces compute with the wrapper function. Each call to compute() now executes the original function, measures elapsed time, prints it, and returns the result.”


Context Managers

Q12. What does with open('f.txt') as f: data = f.read() guarantee even if an exception occurs?

A. The file is read completely B. The data is validated C. No exceptions can occur D. The file is closed automatically

Show answer, D

Answer: D, The with statement ensures the file is closed via exit regardless of whether an exception is raised inside the block. This prevents resource leaks and data corruption.”


Asyncio

Q13. What does await asyncio.gather(task1(), task2()) do compared to calling them sequentially?

A. Runs task1 and task2 concurrently and collects both results B. Runs task1 first, then task2 C. Returns only the first result D. Raises a SyntaxError outside async

Show answer, A

Answer: A, asyncio.gather schedules both coroutines to run concurrently on the event loop. It waits for both to complete and returns a list of results in the order the tasks were passed, not the order they completed.”


Advanced Functions

Q14. What is the output of print(list(map(lambda x, y: x + y, [1,2,3], [4,5,6])))?

A. [5, 7, 9] B. [1, 2, 3, 4, 5, 6] C. [4, 8, 12] D. TypeError: map() takes exactly one argument

Show answer, A

Answer: A, map with two iterables passes corresponding elements as positional arguments to the lambda. It adds element-wise: 1+4=5, 2+5=7, 3+6=9.”

Q15. What does * unpacking do in [1, *[2,3], 4]?

A. Produces [1, 2, 3, 4] B. Produces [1, [2, 3], 4] C. Raises TypeError D. Produces [1, 2, 3, 4] with a nested list

Show answer, A

Answer: A, The * operator unpacks an iterable into individual elements in the enclosing list. [2,3] is unpacked to 2,3, so the result is [1, 2, 3, 4].”

Cross-References

Common Mistakes

Using mutable default arguments: def f(a, b=[]): shares the same list across all calls. Use b=None and b = b or [] inside the function to create a fresh list each time.

Confusing is with ==: is checks identity (same object in memory); == checks equality. Using is for value comparison fails for integers outside the cached range and for strings.

Forgetting that generators are exhausted: A generator can only be iterated once. Iterating it a second time yields nothing. Convert to a list with list(gen) if you need multiple passes.

Advanced Content

This section provides detailed coverage of advanced concepts, including full derivations, proofs, and extended examples.

Derivations and Proofs

Complete mathematical derivations and proofs are provided where appropriate. Each step is explained to ensure understanding of the underlying reasoning.

Extended Examples

Advanced examples demonstrate the application of concepts to complex problems. These examples go beyond standard exam questions to develop deeper understanding.

Research Connections

This material connects to current research and advanced applications in the field. Understanding these connections provides context for the study material.

Prerequisites

Ensure you have mastered the prerequisite material before attempting this advanced content.

Advanced Content

This section provides detailed coverage of advanced concepts, including full derivations, proofs, and extended examples.

Derivations and Proofs

Complete mathematical derivations and proofs are provided where appropriate. Each step is explained to ensure understanding of the underlying reasoning.

Extended Examples

Advanced examples demonstrate the application of concepts to complex problems. These examples go beyond standard exam questions to develop deeper understanding.

Research Connections

This material connects to current research and advanced applications in the field. Understanding these connections provides context for the study material.

Prerequisites

Ensure you have mastered the prerequisite material before attempting this advanced content.

Q?. What is the result of type((1, 2, 3))?