Docsity

Python Crash Course 2026/2027 | 150+ Data Structures & Scripting Questions, Exams of Software Development

Toggle sidebar
bg1
Python Crash Course Systems Design | 150+ Data Structures & Scripting
Questions & Detailed Rationales | Complete Code Test Bank 2026/2027
PY-SYS301: Python Crash Course & Systems Design Prep with Detailed Rationales
*Course Code:* PY-SYS301
*Course Name:* Python Crash Course & Systems Design
*Topic:* Data Structures, Advanced Scripting, and Distributed Systems Architecture
*Academic Year:* 2026/2027
---
📋 STUDY CORE TOPICS OUTLINE
* Topic 1: Python Object Model, Memory Management, and Global Interpreter Lock
(GIL)
* Topic 2: Core & Built-in Data Structures Performance (Lists, Sets, Dicts, Deques,
Heaps)
* Topic 3: Advanced Python Language Constructs (Generators, Iterators, Decorators,
Context Managers, Asyncio)
* Topic 4: System Scripting, IPC, Multiprocessing, and Threading Paradigms
* Topic 5: Scalable Systems Architecture: Load Balancing, Caching, and Rate Limiting
* Topic 6: Distributed Data Storage: Sharding, Replication, Indexing, and CAP Theorem
* Topic 7: Microservices Integration, Event-Driven Architectures, and Message Queues
* Topic 8: Performance Profiling, Memory Optimization, and High-Throughput I/O
Scripting
---
📚 TEXTBOOK ALIGNMENT INDEX
| Section / Module | Focus Area | Question Range |
| :--- | :--- | :--- |
| Part I: Core Foundations | Python Internals, Memory Management, GIL, and Data
Structures | Q1 – Q30 |
| Part II: Intermediate Analysis | Advanced Language Features, Concurrency, and
Low-Level Scripting | Q31 – Q60 |
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download Python Crash Course 2026/2027 | 150+ Data Structures & Scripting Questions and more Exams Software Development in PDF only on Docsity!

Python Crash Course Systems Design | 150+ Data Structures & Scripting

Questions & Detailed Rationales | Complete Code Test Bank 2026/

PY-SYS301: Python Crash Course & Systems Design Prep with Detailed Rationales Course Code: PY-SYS Course Name: Python Crash Course & Systems Design Topic: Data Structures, Advanced Scripting, and Distributed Systems Architecture Academic Year: 2026/

📋 STUDY CORE TOPICS OUTLINE

  • Topic 1: Python Object Model, Memory Management, and Global Interpreter Lock (GIL)
  • Topic 2: Core & Built-in Data Structures Performance (Lists, Sets, Dicts, Deques, Heaps)
  • Topic 3: Advanced Python Language Constructs (Generators, Iterators, Decorators, Context Managers, Asyncio)
  • Topic 4: System Scripting, IPC, Multiprocessing, and Threading Paradigms
  • Topic 5: Scalable Systems Architecture: Load Balancing, Caching, and Rate Limiting
  • Topic 6: Distributed Data Storage: Sharding, Replication, Indexing, and CAP Theorem
  • Topic 7: Microservices Integration, Event-Driven Architectures, and Message Queues
  • Topic 8: Performance Profiling, Memory Optimization, and High-Throughput I/O Scripting

📚 TEXTBOOK ALIGNMENT INDEX

Section / ModuleFocus AreaQuestion Range Part I: Core FoundationsPython Internals, Memory Management, GIL, and Data StructuresQ1 – Q30 Part II: Intermediate AnalysisAdvanced Language Features, Concurrency, and Low-Level ScriptingQ31 – Q60

| Part III: Advanced Syntheses | Subprocesses, Multiprocessing, Async I/O, and File IPC | Q61 – Q90 | | Part IV: Diagnostic Integrations | Systems Design Fundamentals, Caching, Load Balancing, & Databases | Q91 – Q120 | | Part V: Final Case Overviews | Distributed Systems Architecture, Event Streams, & Fault Tolerance | Q121 – Q150 |

Question 1

In CPython, how does the Global Interpreter Lock (GIL) affect the execution of multithreaded CPU-bound Python programs running on multi-core processors? A. It allows true parallel execution of CPU-bound threads across all available hardware cores. B. It restricts execution to a single native thread at a time, preventing multi-core speedup for CPU-bound tasks. C. It automatically converts CPU-bound code into asynchronous coroutines. D. It forces CPython to bypass garbage collection during concurrent execution. CORRECT ANSWER: B. It restricts execution to a single native thread at a time, preventing multi-core speedup for CPU-bound tasks. RATIONALE: The GIL is a mutual-exclusion lock that prevents multiple native threads from executing CPython bytecode simultaneously. For CPU-bound operations, threads contend for the GIL, resulting in execution on a single core. To achieve multi- core parallelism in Python, developers must use process-based concurrency (e.g., multiprocessing) or C extensions that release the GIL.

Question 2

When evaluating average time complexity, what is the amortized runtime cost of appending an element to a standard Python list , and why does table resizing occur? A. O(1) amortized, because CPython allocates extra capacity using an over-allocation strategy when the internal array fills up. B. O(N) amortized, because every single append operation requires allocating a new memory block.

A. The generator function creates a new kernel-level thread for each execution step. B. The interpreter saves the frame object (stack pointer, instruction pointer, and local variables) on the heap when yield is evaluated. C. Generators serialize their environment to disk using implicit pickling on every step. D. The Operating System context-switches the execution context via signal interrupts. CORRECT ANSWER: B. The interpreter saves the frame object (stack pointer, instruction pointer, and local variables) on the heap when yield is evaluated. RATIONALE: Python generator functions utilize frame objects allocated on the heap rather than the standard execution call stack. When execution hits yield, CPython preserves the frame object—including the instruction pointer (f_lasti) and local variables (f_locals)—allowing execution to resume at the exact point on the next call to next().

Question 5

Consider a high-throughput queue requirement where frequent inserts and pops occur at both ends. Why is collections.deque preferred over a standard list for double-ended queue operations? A. deque is backed by a contiguous array that performs instant index-based lookups in O(1) time. B. deque is implemented as a doubly linked block list, enabling O(1) pops/inserts at both ends, whereas list requires O(N) memory shifts for head operations. C. list uses lock-free atomics while deque acquires a mutex on every read. D. deque automatically compresses stored elements using LZ4 algorithms in RAM. CORRECT ANSWER: B. deque is implemented as a doubly linked block list, enabling O(1) pops/inserts at both ends, whereas list requires O(N) memory shifts for head operations. RATIONALE: collections.deque uses a doubly linked list of fixed-size memory blocks. Operations like popleft() and appendleft() take O(1) time because they only modify block pointers. In contrast, prepending to or popping from the front of a standard Python list requires shifting all remaining elements in contiguous RAM, incurring an O(N) performance penalty.

Question 6

How does Python's cyclic garbage collector detect and resolve unreachable cyclic references that cannot be reclaimed by standard reference counting alone? A. By periodically pausing all threads and executing a mark-and-sweep algorithm across the entire system heap. B. By maintaining generation-based collections (Generations 0, 1, and 2) and tracking container objects using doubly linked lists to find isolated reference loops. C. By enforcing that no two mutable objects can store references to each other at compile time. D. By converting all cyclic references into weak references automatically upon assignment. CORRECT ANSWER: B. By maintaining generation-based collections (Generations 0, 1, and 2) and tracking container objects using doubly linked lists to find isolated reference loops. RATIONALE: Primary memory management in CPython uses reference counting. However, reference counts fail to reach zero when objects reference each other cyclically (e.g., A points to B, B points to A). The cyclic garbage collector inspects container objects across three generational pools, tracking trial reference count reductions to identify isolated subgraphs that are unreachable from root objects, and frees them.

Question 7

In Python dictionary architecture (since version 3.6), how was the memory footprint reduced while preserving insertion order iteration? A. By replacing open-addressing hash tables with self-balancing Red-Black trees. B. By splitting storage into a dense dynamic array of key-value pairs and a small array of hash indices pointing into the dense array. C. By dynamically converting dictionary keys to 16-bit integer hashes during assignment. D. By storing all dictionary keys in a shared global lookup index on the heap. CORRECT ANSWER: B. By splitting storage into a dense dynamic array of key- value pairs and a small array of hash indices pointing into the dense array. RATIONALE: Modern CPython dictionaries separate storage into two arrays: a sparse hash table index array (containing byte offsets) and a dense array containing the actual hash, key, and value entries in insertion order. This eliminates empty bucket

RATIONALE: By default, Python instances store attributes in a dynamic dictionary (__dict__), which carries significant memory overhead per object. Defining __slots__ = ('attr1', 'attr2') prevents __dict__ and __weakref__ creation, allocating an optimized, fixed-length array of pointers per instance, substantially reducing memory consumption.

Question 10

When using Python's functools.lru_cache decorator on a function, what underlying mechanism prevents unbounded memory growth? A. It stores outputs in a circular buffer with a predefined capacity, dropping the Least Recently Used item when full. B. It writes expired cache keys directly to temporary disk cache files. C. It executes an internal garbage collection process every 60 seconds. D. It relies on the operating system virtual memory paging mechanism to drop keys. CORRECT ANSWER: A. It stores outputs in a circular buffer with a predefined capacity, dropping the Least Recently Used item when full. RATIONALE: The lru_cache decorator wraps functions with a hash table paired with a doubly linked list. When the maximum configured cache size (maxsize) is reached, adding a new result automatically evicts the entry that was least recently accessed (LRU), maintaining fixed bound limits in memory.

Question 11

Which module in the Python standard library provides an implementation of the binary heap algorithm for building priority queues over standard lists? A. queue.PriorityQueue B. heapq C. bisect D. collections.heap CORRECT ANSWER: B. heapq RATIONALE: The heapq module provides heap queue algorithm functions (min- heaps) that operate directly on standard Python lists in-place. It provides functions such as heappush() and heappop() operating in O(log N) time complexity.

Question 12

In Python exception handling, what is the exact operational distinction between using raise versus raise e inside an except block capturing an exception instance e? A. raise clears the call stack trace, while raise e preserves original line numbers. B. raise re-raises the active exception while preserving the original traceback, whereas raise e can truncate/re-bind the stack trace relative to the catch block. C. raise e executes asynchronously, while raise executes synchronously. D. There is no difference; both produce identical stack frames and bytecode. CORRECT ANSWER: B. raise re-raises the active exception while preserving the original traceback, whereas raise e can truncate/re-bind the stack trace relative to the catch block. RATIONALE: Bare raise re-throws the active exception object directly from the stack frame where it occurred, preserving full original execution stack trace context. Writing raise e re-raises the instance variable e, which can alter stack trace reporting in certain Python execution contexts or nested handlers.

Question 13

Why does string concatenation using the + operator inside a loop scale with O(N^2) complexity in Python, and what is the idiomatic O(N) alternative? A. Strings are mutable; use str.append() instead. B. Strings are immutable, causing each + operation to allocate a new combined string and copy characters; use ''.join(list_of_strings) instead. C. Python strings use reference loops; use sys.intern() instead. D. Iterating over strings forces CPython to lock the GIL; use asyncio.gather() instead. CORRECT ANSWER: B. Strings are immutable, causing each + operation to allocate a new combined string and copy characters; use ''.join(list_of_strings) instead. RATIONALE: Because Python strings are immutable, evaluated str1 + str2 expressions must allocate new contiguous memory arrays and copy all characters from both operands. Doing this in an N-step loop yields 1 + 2 + 3 + ... + N = O(N^2) performance. Collecting strings in a list and invoking ''.join(sequence) calculates total needed capacity once and copies data in O(N) linear time.

What is the primary difference between a shallow copy (copy.copy()) and a deep copy (copy.deepcopy()) when duplicating compound objects like nested lists in Python? A. Shallow copies copy primitive attributes and nested pointers; deep copies recursively copy all nested compound objects. B. Shallow copies duplicate memory on the stack; deep copies place objects in the CPU cache. C. Shallow copies lock GIL execution; deep copies run on background worker threads. D. Shallow copies convert mutable objects into tuples; deep copies convert them into dicts. CORRECT ANSWER: A. Shallow copies copy primitive attributes and nested pointers; deep copies recursively copy all nested compound objects. RATIONALE: A shallow copy constructs a new compound collection object but inserts references into it that point to the child objects contained in the original. A deep copy recursively duplicates every child object down the entire structure tree, creating entirely independent objects in memory.

Question 17

In systems architecture, what design problem is primarily solved by deploying a Load Balancer using a Consistent Hashing algorithm across a cluster of caching servers? A. It guarantees absolute ACID transaction compliance across microservices. B. It minimizes cache miss spikes during node addition or removal by remapping only a small fraction of keys (1/N). C. It encrypts all network payload packets using AES-256 before transmission. D. It prevents SQL injection attacks on backend database layers. CORRECT ANSWER: B. It minimizes cache miss spikes during node addition or removal by remapping only a small fraction of keys (1/N). RATIONALE: Standard modular hashing (hash(key) % N) causes almost all keys to remap to different servers when the node count N changes, creating massive cache invalidation storms. Consistent hashing places both nodes and keys on a logical hash ring. Adding or removing a node only remaps keys belonging to neighboring slots (roughly 1/N of total keys), protecting cache hit ratios.

Question 18

Which database isolation level prevents dirty reads , non-repeatable reads , and phantom reads completely under SQL standard definitions? A. Read Committed B. Repeatable Read C. Serializable D. Read Uncommitted CORRECT ANSWER: C. Serializable RATIONALE: Serializable is the highest database isolation level. It enforces total transaction isolation, executing concurrent transactions as if they occurred in a strict sequential order, entirely eliminating dirty reads, non-repeatable reads, and phantom reads.

Question 19

According to the CAP Theorem for distributed system design, which two properties can a distributed network choose to guarantee simultaneously in the presence of an unavoidable Network Partition (P)? A. Consistency (C) and Availability (A) B. Consistency (C) or Availability (A) C. Performance (P) and Latency (L) D. Durability (D) and Atomicity (A) CORRECT ANSWER: B. Consistency (C) or Availability (A) RATIONALE: The CAP theorem states that when a network partition (P) occurs, a distributed store must choose between Consistency (C) (returning errors or blocking to preserve data correctness across nodes) or Availability (A) (returning local data immediately, risking stale or divergent reads). You cannot have both CP and AP under a network partition.

Question 20

Question 22

Which database indexing data structure is universally favored for disk-based relational databases (such as PostgreSQL or MySQL InnoDB) due to its shallow tree depth and sequential disk I/O optimization? A. Binary Search Tree (BST) B. B+ Tree C. Skip List D. Trie (Prefix Tree) CORRECT ANSWER: B. B+ Tree RATIONALE: B+ Trees store all actual record pointers/data inside leaf nodes linked sequentially in dynamic pages, while internal nodes store only key lookup boundaries. Because leaves have high fan-out and are linked sequentially, disk access requires minimal page seeks, making B+ Trees ideal for block-oriented secondary disk storage.

Question 23

How does a Write-Through Caching pattern maintain consistency between the cache store and backend database storage? A. Applications write data only to the cache; background workers asynchronously sync data to the database hours later. B. Applications write data directly to the database; the cache reads data only upon eviction misses. C. Writes update the cache and the underlying database synchronously in a single combined operation before confirming success to the caller. D. Writes bypass the cache entirely and write exclusively to cold disk archives. CORRECT ANSWER: C. Writes update the cache and the underlying database synchronously in a single combined operation before confirming success to the caller. RATIONALE: In Write-Through caching, the caching layer acts as the primary target for write requests. When data is updated, the system writes to the cache and immediately writes to the underlying data store synchronously before returning success. This guarantees strong cache-DB consistency at the cost of higher write latency.

Question 24

In scalable API rate limiting, how does the Token Bucket Algorithm handle sudden bursts of inbound network traffic compared to a Fixed Window Counter? A. It rejects all burst traffic instantly to keep processing completely flat. B. It permits bursts up to maximum bucket capacity while continuously replenishing tokens at a smooth, constant rate. C. It resets all counter metrics back to zero whenever a burst occurs. D. It routes burst requests to temporary disk storage buffers. CORRECT ANSWER: B. It permits bursts up to maximum bucket capacity while continuously replenishing tokens at a smooth, constant rate. RATIONALE: The Token Bucket algorithm holds tokens up to a predefined capacity limit. Requests consume tokens upon arrival. Tokens are added back to the bucket at a fixed fill rate. If a burst of traffic arrives, it is processed instantly as long as tokens remain in the bucket, preventing the severe border-boundary spikes common in Fixed Window systems.

Question 25

When implementing a distributed lock using Redis across multiple independent master nodes, which algorithm guarantees safety against split-brain scenarios? A. Raft Consensus B. Redlock Algorithm C. Two-Phase Commit (2PC) D. Paxos Broadcast CORRECT ANSWER: B. Redlock Algorithm RATIONALE: Redlock is an algorithm designed by Redis creators for distributed lock management. A client acquires the lock by setting keys with a short TTL across N independent Redis nodes (e.g., 5 nodes). If the client successfully writes the lock key to a majority of nodes (N/2 + 1 = 3) within a timeout window, the lock is safely acquired.

Question 26

What is the core function of a Database Index (e.g., B-Tree index on user_id), and what trade-off does it introduce? A. It speeds up SQL write operations while slowing down SELECT read queries. B. It accelerates data retrieval queries (SELECT) at the expense of additional storage space and reduced write performance (INSERT/UPDATE). C. It encrypts backend tables while reducing system memory usage. D. It forces total serializability on read transactions. CORRECT ANSWER: B. It accelerates data retrieval queries (SELECT) at the expense of additional storage space and reduced write performance (INSERT/UPDATE). RATIONALE: Indexes create side data structures mapping indexed values to physical table rows. This bypasses full-table scans, making reads fast (e.g., O(log N)). However, every write, update, or delete operation must re-index the entries, which increases write operation latency and adds disk storage overhead.

Question 29

In Distributed Systems , what is the primary benefit of deploying Database Read Replicas alongside a single Primary (Master) database instance? A. It guarantees immediate strong consistency for all read operations across geographic regions. B. It offloads read-heavy query workloads from the Primary instance, improving read throughput and system availability. C. It eliminates the need for database backups or transaction logs. D. It prevents network partition failures from occurring. CORRECT ANSWER: B. It offloads read-heavy query workloads from the Primary instance, improving read throughput and system availability. RATIONALE: Many system architectures exhibit read-heavy access patterns (e.g., 95% reads, 5% writes). By replicating write logs from a primary node to multiple read replicas, application read queries can be load-balanced across replicas, reserving primary database CPU/RAM for write transactions.

Question 30

What distinguishes Eventual Consistency from Strong Consistency in scalable distributed storage architectures like Cassandra or Amazon DynamoDB? A. Eventual consistency guarantees that all nodes return identical data instantaneously on every read. B. Eventual consistency allows temporary data divergence across nodes, guaranteeing that all replicas converge to identical values eventually given time without new updates. C. Eventual consistency eliminates all network latency across data centers. D. Eventual consistency requires transactions to use Two-Phase Commits across network segments. CORRECT ANSWER: B. Eventual consistency allows temporary data divergence across nodes, guaranteeing that all replicas converge to identical values eventually given time without new updates. RATIONALE: Eventual consistency trades off immediate accuracy across nodes to optimize write availability and latency. Updates are accepted locally and asynchronously broadcast across replicas. Readers querying different nodes immediately after a write might receive stale data temporarily, but the system converges to unified consistency over time.

Question 31

What is the underlying runtime difference between standard Python Functions and Python Generator Functions initialized using the yield key statement? A. Functions execute to completion and return a value once; Generators instantiate a generator iterator object that executes lazily on step demands. B. Functions run on worker process pools; Generators execute inside the kernel space. C. Functions create immutable scopes; Generators instantiate global state variables. D. Functions require double memory capacity on the thread stack. CORRECT ANSWER: A. Functions execute to completion and return a value once; Generators instantiate a generator iterator object that executes lazily on step demands. RATIONALE: Invoking a function containing yield statements does not immediately execute code. Instead, CPython returns a generator object adhering to the iterator protocol. Executing next() on the generator runs code until a yield is encountered, freezing execution state and returning the yield value lazily.

How can developers safely execute CPU-bound computation tasks within an asyncio application without blocking the primary event loop? A. By marking the computation function with the @asyncio.coroutine decorator. B. By offloading the calculation via loop.run_in_executor() to a ProcessPoolExecutor. C. By wrapping the math operation in an async for loop statement. D. By setting the CPython recursion limit to its maximum value. CORRECT ANSWER: B. By offloading the calculation via loop.run_in_executor() to a ProcessPoolExecutor. RATIONALE: CPU-bound tasks cannot yield execution via network events. To prevent blocking the main event loop, applications use loop.run_in_executor() passing a ProcessPoolExecutor. This dispatches the computation to separate worker processes (which run on separate CPU cores with independent GILs) while returning an awaitable future to the loop.

Question 35

What structural guarantee does Python's Context Manager protocol (__enter__ and __exit__) deliver when dealing with external system resources like File Descriptors or Database Connections? A. It guarantees that the code runs twice as fast compared to standard execution. B. It ensures resource cleanup operations (e.g., close()) execute reliably even if unhandled exceptions are raised inside the block. C. It forces the system to run internal code in a multi-threaded process. D. It converts file stream data into binary network protocols automatically. CORRECT ANSWER: B. It ensures resource cleanup operations (e.g., close()) execute reliably even if unhandled exceptions are raised inside the block. RATIONALE: The with statement guarantees that the __exit__ method executes upon leaving the code block scope, regardless of whether execution completes normally or aborts due to an unhandled exception, preventing resource leaks (such as open file handles or dangling database sockets).

Question 36

What is the structural consequence of using Default Mutable Arguments (e.g., def append_to(element, target_list=[])) in a Python function definition? A. A new empty list is created every single time the function is called without explicit arguments. B. The default list is instantiated once when the function definition is evaluated at module load, sharing state across subsequent calls. C. Python throws a syntax compiler error during script execution initialization. D. The variable is automatically converted into an immutable set. CORRECT ANSWER: B. The default list is instantiated once when the function definition is evaluated at module load, sharing state across subsequent calls. RATIONALE: In Python, default argument expressions are evaluated once when the function definition is bound. If a mutable object (like a list or dictionary) is used as a default, modifications to that object persist across future function calls that rely on the default argument.

Question 37

What functional operational capability does Python's functools.partial object provide developers when constructing modular pipelines? A. It dynamically compiles Python code into native hardware machine code. B. It freezes a specific subset of function arguments and/or keywords, creating a new callable with a reduced positional parameter signature. C. It executes functions across distributed network cluster nodes. D. It caches execution return outputs inside Redis server clusters. CORRECT ANSWER: B. It freezes a specific subset of function arguments and/or keywords, creating a new callable with a reduced positional parameter signature. RATIONALE: functools.partial takes a function and pre-binds fixed values to a subset of its arguments. It returns a new callable object that accepts only the remaining un-bound parameters, facilitating function re-use and event handling pipelines.

Question 38