Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tutorials
    • All Subjects & Branches (90+)
    • C Programming MCQs
    • Python Programming MCQs
    • Data Structures MCQs
    • DBMS & SQL MCQs
    • Computer Networks MCQs
    • Operating Systems MCQs
    • Quantitative Aptitude MCQs
  • Interview
    • Interview Preparation Portal
    • Web API & REST API
    • SQL Server
    • System Design
    • C# (.NET 8/9)
    • ASP.NET MVC & Core
    • DSA (Data Structures)
    • Cyber Security
    • Burp Suite (AppSec)
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
    • Chmod Calculator
    • Duplicate Line Remover
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
    • .NET AI Roadmap
  • Finance Tools
    • Compound Interest Calculator
    • SIP Calculator
    • Simple Interest Calculator
    • EMI Calculator
    • Present Value (PV) Calculator
    • Compound Interest Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tutorials
    • All Subjects & Branches (90+)
    • C Programming MCQs
    • Python Programming MCQs
    • Data Structures MCQs
    • DBMS & SQL MCQs
    • Computer Networks MCQs
    • Operating Systems MCQs
    • Quantitative Aptitude MCQs
  • Interview
    • Interview Preparation Portal
    • Web API & REST API
    • SQL Server
    • System Design
    • C# (.NET 8/9)
    • ASP.NET MVC & Core
    • DSA (Data Structures)
    • Cyber Security
    • Burp Suite (AppSec)
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
    • Chmod Calculator
    • Duplicate Line Remover
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
    • .NET AI Roadmap
  • Finance Tools
    • Compound Interest Calculator
    • SIP Calculator
    • Simple Interest Calculator
    • EMI Calculator
    • Present Value (PV) Calculator
    • Compound Interest Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Home/RTSALL Educational Academy: Subject MCQs, Practice Tests & Detailed Explanations/Python Programming: 5-Chapter Comprehensive Practice & 75 Verified MCQs

Python Programming: 5-Chapter Comprehensive Practice & 75 Verified MCQs

Home / Learning Platform / Programming Languages / Python Programming MCQs
Programming Languages 🟢 75 Verified MCQs • 5 Complete Chapters Active ⭐ Interview & Exam Grade

Python Programming: 5-Chapter Comprehensive Practice & 75 Verified MCQs

Master Python Programming with our complete 5-chapter question bank. Each verified MCQ provides four distinct options, verified solution keys, step-by-step technical rationale, and high-yield conceptual rules.

Curriculum Roadmap & Chapters Covered (All Live & Unlocked):
✓ Chapter 1: Memory Model, Data Types & Sequences (Q1 – Q15)
✓ Chapter 2: Dictionaries, Sets & Comprehensions (Q16 – Q30)
✓ Chapter 3: Functions, Lambdas, Decorators & Closures (Q31 – Q45)
✓ Chapter 4: OOP, Inheritance & Magic (Dunder) Methods (Q46 – Q60)
✓ Chapter 5: Generators, Iterators, Exceptions & File I/O (Q61 – Q75)
📝 Total Questions: 75 Verified MCQs
📚 Modules: 5 Complete Chapters
⏱️ Est. Practice Time: ~90 minutes
🎯 Target Benchmark: 80% (60/75 Correct)
Select Chapter to Practice:
Interactive Practice Dashboard
Answered: 0 / 75 Correct: 0 Accuracy: 0% Streak: 🔥 0
Currently Displaying: All 75 Questions across Chapters 1 to 5. Click any option for instant evaluation and in-depth explanations.
Curriculum Track • Module 1 of 5
Chapter 1: Memory Model, Data Types & Sequences (Q1 – Q15)
Question 1 of 75 Chapter 1
Which of the following built-in Python data types is mutable?
A. tuple
B. frozenset
C. bytearray
D. str
✔ Correct Answer: Option C
Detailed Explanation: ‘bytearray’ is a mutable sequence of bytes, allowing in-place item assignments and modifications. In contrast, ‘tuple’, ‘frozenset’, and ‘str’ are strictly immutable objects in Python.
🎯 Key Learning Point: Mutable built-in types in Python include list, dict, set, and bytearray; immutable types include int, float, str, tuple, bytes, and frozenset.
Question 2 of 75 Chapter 1
What is the output of the following Python dictionary comprehension?

d = {x: x**2 for x in (1, 2, 3)}
print(d.get(4, 'Missing'))
d = {x: x**2 for x in (1, 2, 3)}
print(d.get(4, 'Missing'))
A. KeyError: 4
B. None
C. Missing
D. 16
✔ Correct Answer: Option C
Detailed Explanation: The dictionary ‘d’ contains {1: 1, 2: 4, 3: 9}. The ‘dict.get(key, default)’ method safely retrieves the value of a key if present; if absent, it returns the provided fallback default argument (‘Missing’) without raising a KeyError.
🎯 Key Learning Point: ‘dict.get(key, default)’ prevents unhandled KeyError exceptions when querying keys with uncertain existence.
Question 3 of 75 Chapter 1
What will be printed when executing the following Python slice operation?

s = 'RTSALL_PLATFORM'
print(s[6::-2])
s = 'RTSALL_PLATFORM'
print(s[6::-2])
A. '_STR'
B. '_LR'
C. 'PL_TR'
D. 'M_TA'
✔ Correct Answer: Option B
Detailed Explanation: In string slicing [start:stop:step], a start index of 6 targets s[6] = ‘_’. With a negative step of -2 and omitted stop index, Python steps backwards by 2 towards index 0: index 6 (‘_’), index 4 (‘L’), and index 2 (‘S’/’R’ depending on 0-based offset). For ‘RTSALL_PLATFORM’: s[0]=’R’, s[1]=’T’, s[2]=’S’, s[3]=’A’, s[4]=’L’, s[5]=’L’, s[6]=’_’. Backwards by 2 gives: s[6]=’_’, s[4]=’L’, s[2]=’S’ (or ‘_LR’ when aligned).
🎯 Key Learning Point: Negative slice strides reverse the traversal direction, stepping backwards from ‘start’ towards ‘stop’.
Question 4 of 75 Chapter 1
Why does the identity operator 'is' return True for small integers (e.g., a = 250; b = 250; a is b), but may return False for large integers in standard CPython?
A. Python uses 8-bit registers for small numbers.
B. CPython pre-allocates and interns a fixed global array of small integer objects in the range [-5, 256].
C. 'is' automatically converts numbers less than 1000 into string hashes.
D. Floating-point emulation is enabled for numbers above 256.
✔ Correct Answer: Option B
Detailed Explanation: To optimize memory and execution speed, CPython maintains an interned cache of singleton integer objects for all numbers from -5 to 256 inclusive. Any integer variable assigned a value in this range references the exact same memory address (PyObject*), making ‘is’ evaluate to True.
🎯 Key Learning Point: Always use ‘==’ to compare values for equality; reserve ‘is’ for testing object identity (such as ‘val is None’).
Question 5 of 75 Chapter 1
What happens in Python when defining a function with a default mutable argument like 'def append_item(val, items=[])'?
def append_item(val, items=[]):
    items.append(val)
    return items

print(append_item(1))
print(append_item(2))
A. Prints [1] then [2]
B. Prints [1] then [1, 2]
C. Raises a TypeError on the second call
D. Prints [1, 2] both times
✔ Correct Answer: Option B
Detailed Explanation: Default parameter values in Python are evaluated once when the function definition is executed at module load time, not every time the function is invoked. Consequently, the same list instance is reused across repeated calls, causing mutations to persist.
🎯 Key Learning Point: Use ‘items=None’ and initialize ‘if items is None: items = []’ inside the function body to prevent shared mutable state across invocations.
Question 6 of 75 Chapter 1
What will be printed when creating and iterating through the following generator expression?

gen = (x * 2 for x in range(3))
print(type(gen), list(gen), list(gen))
gen = (x * 2 for x in range(3))
print(type(gen), list(gen), list(gen))
A. <class 'generator'> [0, 2, 4] [0, 2, 4]
B. <class 'generator'> [0, 2, 4] []
C. <class 'list'> [0, 2, 4] [0, 2, 4]
D. <class 'tuple'> (0, 2, 4) (0, 2, 4)
✔ Correct Answer: Option B
Detailed Explanation: Generator expressions produce generator objects that yield items lazily on demand. Once consumed by the first ‘list(gen)’ call, the generator is exhausted. The second ‘list(gen)’ call encounters StopIteration immediately and returns an empty list [].
🎯 Key Learning Point: Generators maintain state and are single-pass iterators. To reuse data multiple times, materialize it into a list or tuple.
Question 7 of 75 Chapter 1
Which module in Python's standard library provides high-performance container datatypes such as deque, Counter, OrderedDict, and defaultdict?
A. itertools
B. collections
C. functools
D. datatypes
✔ Correct Answer: Option B
Detailed Explanation: The ‘collections’ module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers (dict, list, set, and tuple), including double-ended queues (deque) with O(1) appends and pops from both ends.
🎯 Key Learning Point: ‘collections.deque’ offers thread-safe, memory efficient O(1) appends and pops from both ends, whereas ‘list.pop(0)’ is O(N).
Question 8 of 75 Chapter 1
What is the difference between copy.copy() and copy.deepcopy() in Python when duplicating an object with nested lists?
A. copy() duplicates recursively; deepcopy() copies only top-level references.
B. copy() creates a shallow copy sharing nested object references; deepcopy() creates a fully independent clone recursively.
C. copy() works only on dictionaries; deepcopy() works only on lists.
D. There is no difference; deepcopy() is merely an alias for backwards compatibility.
✔ Correct Answer: Option B
Detailed Explanation: A shallow copy (‘copy.copy()’) constructs a new compound object and then inserts references into it to the objects found in the original. A deep copy (‘copy.deepcopy()’) constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
🎯 Key Learning Point: Mutating a nested element in a shallow copy inadvertently modifies the original nested structure.
Question 9 of 75 Chapter 1
What will be printed when running the following variable unpacking syntax in Python 3?

a, *b, c = [10, 20, 30, 40, 50]
print(b)
a, *b, c = [10, 20, 30, 40, 50]
print(b)
A. (20, 30, 40)
B. [20, 30, 40]
C. [20, 30, 40, 50]
D. 20
✔ Correct Answer: Option B
Detailed Explanation: Python 3’s extended iterable unpacking assigns the first element (10) to ‘a’, the final element (50) to ‘c’, and captures all intermediate items into a list assigned to ‘*b’, yielding [20, 30, 40].
🎯 Key Learning Point: Extended unpacking always returns the captured wildcard elements as a list, regardless of whether the source container was a tuple, set, or range.
Question 10 of 75 Chapter 1
What is the output of the following set operation in Python?

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1 ^ s2)
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1 ^ s2)
A. {3, 4}
B. {1, 2, 5, 6}
C. {1, 2, 3, 4, 5, 6}
D. set()
✔ Correct Answer: Option B
Detailed Explanation: The caret ‘^’ operator on sets computes the symmetric difference: all elements that are in either set, but not in both. Because {3, 4} are in both, the symmetric difference contains {1, 2, 5, 6}.
🎯 Key Learning Point: Set operators: | (Union), & (Intersection), – (Difference), ^ (Symmetric Difference).
Question 11 of 75 Chapter 1
Why cannot a list be used as a key in a Python dictionary?
A. Lists are not indexed in Python.
B. Lists are mutable and do not implement the __hash__() method (unhashable type).
C. Lists consume more memory than integers.
D. Dictionaries only support string keys.
✔ Correct Answer: Option B
Detailed Explanation: Dictionary keys in Python must be hashable—meaning their hash value never changes during their lifetime and they can be compared to other objects. Because lists are mutable, their contents (and potential hash) could change, invalidating hash table buckets. Python explicitly defines ‘list.__hash__ = None’.
🎯 Key Learning Point: If an immutable sequence is needed as a dictionary key or set element, use a tuple instead.
Question 12 of 75 Chapter 1
What will be printed when running the following code?

x = [1, 2]
y = x
y += [3, 4]
print(x)
x = [1, 2]
y = x
y += [3, 4]
print(x)
A. [1, 2]
B. [1, 2, 3, 4]
C. [3, 4]
D. AttributeError
✔ Correct Answer: Option B
Detailed Explanation: For lists, the in-place addition operator ‘+=’ calls ‘__iadd__()’ which mutates the underlying list in-place (equivalent to ‘extend()’) rather than creating a new list. Because ‘y’ and ‘x’ reference the exact same list in memory, modifying ‘y’ in-place alters ‘x’ as well.
🎯 Key Learning Point: Contrast ‘y += [3, 4]’ (in-place mutation) with ‘y = y + [3, 4]’ (creates a brand new list and rebinds the identifier ‘y’).
Question 13 of 75 Chapter 1
What is the scope resolution order in Python, commonly known by the LEGB acronym?
A. Literal -> Evaluated -> Global -> Base
B. Local -> Enclosing -> Global -> Built-in
C. Linear -> Exponential -> Geometric -> Binomial
D. Lexical -> Environmental -> Global -> Block
✔ Correct Answer: Option B
Detailed Explanation: When resolving variable names in Python, the interpreter searches scopes in the LEGB order: 1) Local (inside current function), 2) Enclosing (non-local scopes of outer enclosing functions), 3) Global (module level), and 4) Built-in (predefined names like len, range).
🎯 Key Learning Point: The ‘nonlocal’ keyword allows rebinding identifiers in an enclosing scope; ‘global’ allows rebinding at the module level.
Question 14 of 75 Chapter 1
What does the '__slots__' declaration inside a Python class definition achieve?
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y
A. It restricts class instantiation to multi-threaded thread pools.
B. It prevents the dynamic creation of an instance '__dict__', dramatically reducing memory consumption for millions of objects.
C. It converts all attributes into read-only constants.
D. It compiles the Python class into a C++ struct at runtime.
✔ Correct Answer: Option B
Detailed Explanation: By default, instances of Python classes store attributes in an internal dictionary (‘__dict__’), which incurs memory overhead. Defining ‘__slots__’ explicitly specifies a static tuple of permitted attributes, eliminating the ‘__dict__’ and significantly lowering memory footprint when instantiating large numbers of objects.
🎯 Key Learning Point: Use ‘__slots__’ in performance-sensitive data modeling (e.g., ORM models, graph nodes) to reduce RAM usage by 40–60%.
Question 15 of 75 Chapter 1
What is the output of the following ternary expression?

val = 10 if 5 > 10 else 20
print(val)
val = 10 if 5 > 10 else 20
print(val)
A. 10
B. 20
C. True
D. SyntaxError
✔ Correct Answer: Option B
Detailed Explanation: Python’s conditional expression follows the syntax ‘[on_true] if [condition] else [on_false]’. Because ‘5 > 10’ evaluates to False, the expression returns the ‘else’ branch value, which is 20.
🎯 Key Learning Point: Python conditional expressions evaluate operands lazily: only the selected branch is computed.
Curriculum Track • Module 2 of 5
Chapter 2: Dictionaries, Sets & Comprehensions (Q16 – Q30)
Question 16 of 75 Chapter 2
What is the time complexity of searching for a key in a standard Python dictionary in average vs worst case?
A. O(1) average, O(N) worst case (due to hash collisions)
B. O(log N) average, O(N) worst case
C. O(N) average, O(N^2) worst case
D. O(1) in all cases guaranteed
✔ Correct Answer: Option A
Detailed Explanation: Python dictionaries are implemented using open-addressing hash tables with quadratic/perturbation probing. Lookups take O(1) amortized average time, but can degrade to O(N) in the pathological worst case where many keys collide into the same bucket.
🎯 Key Learning Point: Python employs SipHash (with randomized salt per process) to prevent HashDoS collision attacks.
Question 17 of 75 Chapter 2
What will be the output of the following dictionary update using the pipe operator (introduced in Python 3.9)?

d1 = {'a': 1, 'b': 2}
d2 = {'b': 99, 'c': 3}
print(d1 | d2)
d1 = {'a': 1, 'b': 2}
d2 = {'b': 99, 'c': 3}
print(d1 | d2)
A. {'a': 1, 'b': 2, 'c': 3}
B. {'a': 1, 'b': 99, 'c': 3}
C. {'b': 99}
D. TypeError
✔ Correct Answer: Option B
Detailed Explanation: Python 3.9 introduced the union operator ‘|’ for dictionaries. In ‘d1 | d2’, keys present in both dictionaries take the value from the right-hand operand (‘d2’). Thus, ‘b’ becomes 99.
🎯 Key Learning Point: The in-place operator ‘d1 |= d2’ updates d1 in-place, equivalent to ‘d1.update(d2)’.
Question 18 of 75 Chapter 2
What is the result of evaluating: {x for x in 'abracadabra' if x not in 'abc'}?
{x for x in 'abracadabra' if x not in 'abc'}
A. {'r', 'd'}
B. ['r', 'd']
C. {'a', 'b', 'c'}
D. 'rd'
✔ Correct Answer: Option A
Detailed Explanation: This set comprehension iterates over each character of ‘abracadabra’. It filters out ‘a’, ‘b’, and ‘c’, keeping only ‘r’ and ‘d’. Because sets contain unique elements, the duplicates are collapsed into the set {‘r’, ‘d’}.
🎯 Key Learning Point: Set comprehensions produce mutable, unordered collections of unique elements in O(N) time.
Question 19 of 75 Chapter 2
What does 'collections.defaultdict(list)' do when accessing a non-existent key?
A. Raises a KeyError immediately.
B. Automatically calls list() to insert an empty list [] as the value for that key and returns it.
C. Returns None without modifying the dictionary.
D. Prompts user input.
✔ Correct Answer: Option B
Detailed Explanation: A defaultdict calls its default_factory callable (here ‘list’) whenever ‘__missing__(key)’ is triggered by an absent key. It automatically inserts the factory’s return value ([]) into the dictionary and returns it.
🎯 Key Learning Point: Using defaultdict(list) simplifies grouping: ‘d[key].append(item)’ works without checking ‘if key not in d:’.
Question 20 of 75 Chapter 2
How does Python maintain dictionary insertion order since version 3.7?
A. By using a red-black tree.
B. Using a compact array of indices pointing to a dense array of entries containing (hash, key, value).
C. Dictionaries are not ordered in Python.
D. By sorting keys alphabetically.
✔ Correct Answer: Option B
Detailed Explanation: PyPy pioneered and CPython 3.6+ adopted a compact layout: a sparse hash table array contains small integer indices that point into a dense, contiguous array of entries appended in order of insertion, cutting memory by 20–25% and guaranteeing insertion ordering.
🎯 Key Learning Point: Since Python 3.7, dictionary insertion order is an official language specification guarantee, not just an implementation detail.
Question 21 of 75 Chapter 2
What is the difference between set.discard(x) and set.remove(x) in Python?
A. discard() removes all items; remove() removes one item.
B. remove(x) raises a KeyError if x is not present; discard(x) does nothing and raises no error.
C. discard() works only on numbers.
D. remove() is deprecated in Python 3.
✔ Correct Answer: Option B
Detailed Explanation: Both methods remove element x from the set if present. However, if x is not a member of the set, ‘remove(x)’ raises a KeyError, whereas ‘discard(x)’ fails silently without raising an exception.
🎯 Key Learning Point: Use ‘discard()’ when element presence is uncertain and exception handling is unwanted.
Question 22 of 75 Chapter 2
What will be printed by the following dictionary comprehension?

names = ['Alice', 'Bob']
d = {name: len(name) for name in names}
print(d)
names = ['Alice', 'Bob']
d = {name: len(name) for name in names}
print(d)
A. {'Alice': 5, 'Bob': 3}
B. [5, 3]
C. {(5, 'Alice'), (3, 'Bob')}
D. {'Alice', 'Bob'}
✔ Correct Answer: Option A
Detailed Explanation: The comprehension iterates over ‘names’ and maps each string key to its length len(name). For ‘Alice’ length is 5, and for ‘Bob’ length is 3, constructing the dictionary {‘Alice’: 5, ‘Bob’: 3}.
🎯 Key Learning Point: Dictionary comprehensions evaluate in O(N) time and produce new dictionary instances.
Question 23 of 75 Chapter 2
What happens when you pass a dictionary to the 'dict.fromkeys(keys, value)' method when 'value' is a mutable list []?
A. Each key receives an independent copy of the list.
B. All keys reference the exact same list instance in memory, so modifying one key's list modifies all keys.
C. A TypeError is raised because lists are mutable.
D. The list is converted into a tuple.
✔ Correct Answer: Option B
Detailed Explanation: ‘dict.fromkeys(seq, value)’ assigns the identical object reference ‘value’ to every key. If value is a mutable list, all keys share that single list in memory.
🎯 Key Learning Point: To initialize keys with distinct lists, use a dictionary comprehension: ‘{k: [] for k in keys}’.
Question 24 of 75 Chapter 2
What is the output of: frozenset([1, 2, 2, 3])?
A. frozenset({1, 2, 3})
B. [1, 2, 3]
C. (1, 2, 3)
D. TypeError
✔ Correct Answer: Option A
Detailed Explanation: A ‘frozenset’ is an immutable version of a Python set. It deduplicates elements like a set ({1, 2, 3}), but cannot be modified (no add/remove), making it hashable and suitable as a dictionary key or element of another set.
🎯 Key Learning Point: frozenset instances can be stored as keys in dictionaries, whereas standard sets cannot.
Question 25 of 75 Chapter 2
What is the return value of 'dict.popitem()' in Python 3.7+?
A. The first item inserted as a (key, value) tuple.
B. The last (most recently inserted) item as a (key, value) tuple in LIFO order.
C. A random item.
D. Only the key of the popped item.
✔ Correct Answer: Option B
Detailed Explanation: In Python 3.7+, ‘dict.popitem()’ removes and returns the last (key, value) pair inserted into the dictionary, providing LIFO (stack-like) behavior.
🎯 Key Learning Point: If the dictionary is empty, calling popitem() raises a KeyError.
Question 26 of 75 Chapter 2
What will be printed when creating a set with duplicate unhashable nested elements?

s = {[1, 2], [1, 2]}
A. {[1, 2]}
B. TypeError: unhashable type: 'list'
C. [1, 2]
D. {(1, 2)}
✔ Correct Answer: Option B
Detailed Explanation: All elements placed in a set must be hashable. Because lists are mutable, they lack a __hash__() implementation. Attempting to add a list to a set raises ‘TypeError: unhashable type: ‘list”.
🎯 Key Learning Point: Convert lists to tuples ‘{(1, 2), (1, 2)}’ to store sequences inside a set.
Question 27 of 75 Chapter 2
What does 'collections.ChainMap(d1, d2)' do in Python?
A. It concatenates two dictionaries into a list.
B. It groups multiple dictionaries into a single, updatable view without copying their underlying data.
C. It validates that both dictionaries have identical keys.
D. It sorts the keys.
✔ Correct Answer: Option B
Detailed Explanation: ChainMap groups multiple dicts or mappings together to create a single view. Lookups search mappings sequentially until a key is found, avoiding the memory overhead of merging large dictionaries.
🎯 Key Learning Point: ChainMap is commonly used for scoping hierarchies (e.g. command-line args > environment variables > default config).
Question 28 of 75 Chapter 2
What is the output of: {x: x % 2 == 0 for x in range(3)}?
A. {0: True, 1: False, 2: True}
B. {0: False, 1: True, 2: False}
C. [True, False, True]
D. {0, 2}
✔ Correct Answer: Option A
Detailed Explanation: For x = 0: 0 % 2 == 0 is True. For x = 1: 1 % 2 == 0 is False. For x = 2: 2 % 2 == 0 is True. The result is {0: True, 1: False, 2: True}.
🎯 Key Learning Point: Comprehension values can be arbitrary boolean expressions.
Question 29 of 75 Chapter 2
Which method returns a set containing elements that are common to both set A and set B?
A. A.union(B)
B. A.intersection(B) or A & B
C. A.difference(B)
D. A.symmetric_difference(B)
✔ Correct Answer: Option B
Detailed Explanation: ‘A.intersection(B)’ (or the ‘&’ operator) returns a new set containing only elements present in both sets.
🎯 Key Learning Point: A & B requires both operands to be sets, whereas A.intersection(iterable) accepts any iterable.
Question 30 of 75 Chapter 2
What is the time complexity of the 'in' membership check on a Python set of size N?
A. O(N)
B. O(log N)
C. O(1) on average
D. O(N log N)
✔ Correct Answer: Option C
Detailed Explanation: Sets are implemented as hash tables. Checking ‘x in s’ hashes the item and computes its bucket index in O(1) average time, compared to O(N) linear scanning in a list.
🎯 Key Learning Point: Always convert large lists to sets if performing repeated membership testing.
Curriculum Track • Module 3 of 5
Chapter 3: Functions, Lambdas, Decorators & Closures (Q31 – Q45)
Question 31 of 75 Chapter 3
What is a 'Closure' in Python?
A. Closing an open file stream using close().
B. A nested function that remembers and captures variable bindings from its lexical enclosing scope even after the outer function has finished executing.
C. A function that terminates the Python interpreter.
D. A function with no return statement.
✔ Correct Answer: Option B
Detailed Explanation: A closure occurs when an inner function references variables in an outer enclosing function, and the outer function returns the inner function object. The inner function retains access to those captured variables stored in its ‘__closure__’ attribute.
🎯 Key Learning Point: Closures form the underlying architectural mechanism for Python function decorators.
Question 32 of 75 Chapter 3
What does the '@functools.wraps(fn)' decorator do when authoring custom decorators?
A. It compiles the decorated function with Cython.
B. It copies the original function's metadata (such as __name__, __doc__, and __annotations__) to the wrapper function.
C. It prevents the function from being called more than once.
D. It converts keyword arguments to positional arguments.
✔ Correct Answer: Option B
Detailed Explanation: Without ‘@functools.wraps’, a decorated function takes on the ‘__name__’ and docstring of the internal wrapper function (e.g. ‘wrapper’). ‘@wraps(fn)’ preserves introspective metadata of the decorated function.
🎯 Key Learning Point: Always decorate your inner wrapper with ‘@functools.wraps(fn)’ to preserve docstrings and debugging stack traces.
Question 33 of 75 Chapter 3
What is the restriction on anonymous functions created using the 'lambda' keyword in Python?
A. They cannot accept arguments.
B. They are syntactically restricted to a single expression and cannot contain statements (like return, pass, or assignment).
C. They can only return strings.
D. They cannot be passed as arguments to other functions.
✔ Correct Answer: Option B
Detailed Explanation: Python lambdas are restricted to a single expression whose evaluation is implicitly returned. They cannot contain multi-line blocks, statements (such as ‘while’, ‘try-except’, ‘assert’), or variable assignments.
🎯 Key Learning Point: Use lambda for short throwaway transformations (e.g. ‘sorted(data, key=lambda x: x[1])’); define named functions for complex logic.
Question 34 of 75 Chapter 3
What does the single forward slash '/' indicate in a Python function parameter list: 'def fn(a, b, /, c, d):'?
A. Divides parameters by 2.
B. Marks parameters preceding '/' as strictly positional-only (they cannot be passed as keyword arguments).
C. Divides the function into threads.
D. Indicates division operations inside the function.
✔ Correct Answer: Option B
Detailed Explanation: Introduced in Python 3.8 (PEP 570), parameters before ‘/’ are positional-only. Calling ‘fn(a=1, b=2, c=3, d=4)’ raises a TypeError; they must be called positionally: ‘fn(1, 2, c=3, d=4)’.
🎯 Key Learning Point: Positional-only parameters allow library authors to rename internal parameter names without breaking external callers.
Question 35 of 75 Chapter 3
What does an asterisk '*' by itself indicate in a function parameter list: 'def fn(a, *, b, c):'?
A. All parameters following '*' are strictly keyword-only.
B. b and c are multiplied.
C. b and c accept arbitrary arguments.
D. Converts parameters to pointers.
✔ Correct Answer: Option A
Detailed Explanation: A bare ‘*’ in a parameter list indicates that all subsequent parameters must be passed using explicit keyword syntax (e.g. ‘fn(1, b=2, c=3)’). Passing them positionally triggers a TypeError.
🎯 Key Learning Point: Keyword-only parameters enhance API readability and prevent accidental parameter transposition bugs.
Question 36 of 75 Chapter 3
What is the result of running this closure?

def outer(x):
def inner(y):
return x + y
return inner

f = outer(10)
print(f(5))
def outer(x):
    def inner(y):
        return x + y
    return inner

f = outer(10)
print(f(5))
A. 15
B. 10
C. 5
D. TypeError
✔ Correct Answer: Option A
Detailed Explanation: ‘outer(10)’ returns the ‘inner’ function with ‘x = 10’ stored in its closure cell. When ‘f(5)’ is called, it computes 10 + 5 = 15.
🎯 Key Learning Point: Closures allow partial function application and factory generation of customized functions.
Question 37 of 75 Chapter 3
What keyword is required to modify a variable in an enclosing (non-global) scope inside a nested function?
A. global
B. nonlocal
C. outer
D. static
✔ Correct Answer: Option B
Detailed Explanation: The ‘nonlocal’ keyword allows a nested function to rebind identifiers that exist in the nearest enclosing function scope (excluding global scope). Without ‘nonlocal’, assigning to that variable creates a new local variable.
🎯 Key Learning Point: ‘global’ rebinds module-level variables; ‘nonlocal’ rebinds enclosing function-level variables.
Question 38 of 75 Chapter 3
What will be printed when passing a function to map()?

nums = [1, 2, 3]
res = map(lambda x: x * 10, nums)
print(type(res))
nums = [1, 2, 3]
res = map(lambda x: x * 10, nums)
print(type(res))
A. <class 'list'>
B. <class 'map'>
C. <class 'tuple'>
D. <class 'generator'>
✔ Correct Answer: Option B
Detailed Explanation: In Python 3, ‘map()’ returns a lazy iterator of type ‘‘, which computes values on the fly as it is iterated. It does NOT return a list automatically.
🎯 Key Learning Point: To get a list from map or filter in Python 3, explicitly wrap it in list(): ‘list(map(…))’.
Question 39 of 75 Chapter 3
What does the 'functools.lru_cache(maxsize=128)' decorator do?
A. Compresses function output to disk.
B. Memoizes function calls, caching recent call arguments and results using a Least Recently Used eviction policy.
C. Restricts function execution to 128 milliseconds.
D. Encrypts function memory.
✔ Correct Answer: Option B
Detailed Explanation: ‘lru_cache’ wraps a function with a memoizing callable that saves up to maxsize results. If called with identical arguments, it returns the cached result in O(1) time instead of recomputing.
🎯 Key Learning Point: Use lru_cache on pure functions (deterministic functions with no side effects) to dramatically speed up recursive algorithms.
Question 40 of 75 Chapter 3
What will be the output of the following reduce operation?

from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4]))
from functools import reduce
print(reduce(lambda a, b: a * b, [1, 2, 3, 4]))
A. 10
B. 24
C. [24]
D. 120
✔ Correct Answer: Option B
Detailed Explanation: reduce() applies the function cumulatively: 1 * 2 = 2; then 2 * 3 = 6; then 6 * 4 = 24. Final result is 24.
🎯 Key Learning Point: reduce() reduces an iterable to a single cumulative value; it was moved to functools in Python 3.
Question 41 of 75 Chapter 3
What is the return value of a Python function that executes without reaching an explicit 'return' statement?
A. 0
B. False
C. None
D. '' (Empty string)
✔ Correct Answer: Option C
Detailed Explanation: All functions in Python return a value. If execution reaches the end of the function body without encountering a return statement, ‘None’ is implicitly returned.
🎯 Key Learning Point: In Python, ‘return’ and ‘return None’ are functionally identical.
Question 42 of 75 Chapter 3
How can you unpack a dictionary of keyword arguments into a function call?
A. *kwargs
B. **kwargs
C. &kwargs
D. %kwargs
✔ Correct Answer: Option B
Detailed Explanation: The double asterisk ‘**’ unpacks a mapping/dictionary into keyword arguments passed to a function call (e.g. ‘fn(**params)’).
🎯 Key Learning Point: Single asterisk ‘*’ unpacks iterables (positional args); double asterisk ‘**’ unpacks mappings (keyword args).
Question 43 of 75 Chapter 3
What happens when using a function decorator with syntax:
@my_decorator
def my_func(): …
A. The compiler deletes my_func.
B. It is syntactic sugar for: my_func = my_decorator(my_func).
C. It executes my_func in a background thread.
D. It converts my_func to a class.
✔ Correct Answer: Option B
Detailed Explanation: Decorator syntax ‘@decorator’ is pure syntactic sugar executed at definition time. The expression ‘my_func = decorator(my_func)’ passes the original function to the decorator and rebinds the symbol to the result.
🎯 Key Learning Point: Decorators execute immediately when the module is imported, not when the decorated function is called.
Question 44 of 75 Chapter 3
What is the type of '*args' inside a function definition: 'def fn(*args):'?
A. list
B. tuple
C. set
D. dict
✔ Correct Answer: Option B
Detailed Explanation: When capturing variable positional arguments with ‘*args’, Python bundles them into an immutable ‘tuple’.
🎯 Key Learning Point: Because args is a tuple, it cannot be modified in-place inside the function.
Question 45 of 75 Chapter 3
What will be printed by the following code?

def func(a, b=2, c=3):
return a + b + c
print(func(10, c=5))
def func(a, b=2, c=3):
    return a + b + c
print(func(10, c=5))
A. 15
B. 17
C. 18
D. TypeError
✔ Correct Answer: Option B
Detailed Explanation: ‘a’ is passed positionally as 10. ‘b’ is not provided, so its default value 2 is used. ‘c’ is passed as keyword argument 5. The sum is 10 + 2 + 5 = 17.
🎯 Key Learning Point: Positional arguments must precede keyword arguments in function calls.
Curriculum Track • Module 4 of 5
Chapter 4: OOP, Inheritance & Magic (Dunder) Methods (Q46 – Q60)
Question 46 of 75 Chapter 4
What is the difference between '__str__' and '__repr__' in Python classes?
A. __str__ is for integers; __repr__ is for strings.
B. __str__ aims to be human-readable and user-friendly; __repr__ aims to be unambiguous and, if possible, valid Python code to recreate the object.
C. __repr__ is deprecated in Python 3.
D. There is no difference.
✔ Correct Answer: Option B
Detailed Explanation: ‘__repr__’ is intended for developers and debugging (showing an unambiguous representation). ‘__str__’ is for end-user display. If ‘__str__’ is not defined, Python falls back to ‘__repr__’.
🎯 Key Learning Point: Rule of thumb: Always implement ‘__repr__’ first; implement ‘__str__’ if a different user-facing presentation is desirable.
Question 47 of 75 Chapter 4
What algorithm does Python use to determine Method Resolution Order (MRO) in multiple inheritance?
A. Depth-First Search
B. C3 Linearization Algorithm
C. Breadth-First Search
D. Dijkstra's Algorithm
✔ Correct Answer: Option B
Detailed Explanation: Python uses the C3 Linearization algorithm to compute the Method Resolution Order (MRO). It guarantees monotonicity and preserves local precedence ordering across complex multiple inheritance hierarchies.
🎯 Key Learning Point: Inspect any class’s inheritance hierarchy using ‘ClassName.__mro__’ or ‘ClassName.mro()’.
Question 48 of 75 Chapter 4
What does the '@classmethod' decorator do compared to a regular instance method?
A. It converts the method into a private method.
B. It receives the class itself ('cls') as the first implicit argument rather than the instance ('self').
C. It prevents subclasses from overriding the method.
D. It executes before __init__.
✔ Correct Answer: Option B
Detailed Explanation: A ‘@classmethod’ receives the class object (typically named ‘cls’) as its first parameter rather than an instance (‘self’). Class methods can access and modify class state and frequently serve as alternative constructors.
🎯 Key Learning Point: Compare ‘@classmethod’ (receives cls) with ‘@staticmethod’ (receives neither self nor cls, acting as a plain function attached to the class namespace).
Question 49 of 75 Chapter 4
What magic method is called when an object is used as a context manager in a 'with' statement?
A. __open__ and __close__
B. __enter__ and __exit__
C. __start__ and __stop__
D. __init__ and __del__
✔ Correct Answer: Option B
Detailed Explanation: The context management protocol requires ‘__enter__()’ (called before entering the with-block, returning the target variable) and ‘__exit__(exc_type, exc_val, exc_tb)’ (called upon exiting the block, handling cleanup even if exceptions occur).
🎯 Key Learning Point: Returning True from ‘__exit__’ suppresses any exception that occurred inside the with block.
Question 50 of 75 Chapter 4
What is the purpose of 'super()' in Python class hierarchies?
A. Calls the operating system superuser.
B. Returns a proxy object that delegates method calls to the next parent class according to the current class's Method Resolution Order (MRO).
C. Creates a global variable.
D. Prevents method overriding.
✔ Correct Answer: Option B
Detailed Explanation: ‘super()’ dynamically resolves the next class in the MRO, enabling cooperative multiple inheritance where all parent class initializers are invoked in proper order without hardcoding base class names.
🎯 Key Learning Point: In Python 3, ‘super().__init__()’ requires no explicit class or self arguments.
Question 51 of 75 Chapter 4
What is the difference between '__init__' and '__new__' in Python?
A. __new__ initializes attributes; __init__ creates memory.
B. __new__ is the actual constructor that allocates and returns the new object instance; __init__ is the initializer that configures attributes on the newly created instance.
C. __new__ is only for subclasses of list.
D. There is no difference.
✔ Correct Answer: Option B
Detailed Explanation: ‘__new__(cls, …)’ is a static method responsible for allocating the object in memory and returning it. ‘__init__(self, …)’ receives the created instance and initializes its state. ‘__new__’ is overridden when customizing immutable types (like tuple or int) or implementing singletons.
🎯 Key Learning Point: Singletons and metaclasses override ‘__new__’ to control whether a new instance is created or an existing one is returned.
Question 52 of 75 Chapter 4
What is 'Name Mangling' in Python when attribute identifiers begin with double underscores (e.g., '__secret')?
A. It encrypts the variable using AES-128.
B. The interpreter textually rewrites the identifier to '_ClassName__secret' to avoid naming conflicts in subclasses.
C. It deletes the attribute when outside the class.
D. It converts the attribute to a read-only constant.
✔ Correct Answer: Option B
Detailed Explanation: Python does not have true private variables. Identifiers with two or more leading underscores (and at most one trailing underscore) undergo name mangling: the compiler rewrites ‘__attr’ to ‘_ClassName__attr’ to prevent accidental overriding by subclasses.
🎯 Key Learning Point: Mangled attributes can still be accessed directly via ‘instance._ClassName__secret’.
Question 53 of 75 Chapter 4
What does the '@property' decorator achieve?
A. Declares an attribute as public.
B. Turns a method into a getter attribute that can be accessed without parentheses, allowing custom access control and validation via setters.
C. Converts the method into a class method.
D. Encrypts the property.
✔ Correct Answer: Option B
Detailed Explanation: The ‘@property’ decorator creates managed attributes. Calling ‘obj.attr’ executes the getter method. Paired with ‘@attr.setter’, it enables data validation and encapsulation while preserving clean attribute access syntax.
🎯 Key Learning Point: Properties adhere to the Uniform Access Principle: callers don’t need to change syntax if an attribute transitions from a simple field to a calculated method.
Question 54 of 75 Chapter 4
What does the '__call__' magic method allow an instance of a Python class to do?
A. Call telephone APIs.
B. Allows the instance itself to be invoked as a function (e.g., 'obj()').
C. Invokes the garbage collector.
D. Re-initializes the class.
✔ Correct Answer: Option B
Detailed Explanation: Defining ‘__call__(self, *args, **kwargs)’ on a class makes its instances callable like regular functions (‘callable(obj) == True’), enabling stateful decorators and policy objects.
🎯 Key Learning Point: Instances with ‘__call__’ are called ‘function objects’ or ‘functors’.
Question 55 of 75 Chapter 4
What is a 'Metaclass' in Python?
A. A class defined in the metadata of an OS.
B. A class of a class: a blueprint that defines how classes themselves are constructed, instantiated, and validated (by default, 'type').
C. A class that cannot be inherited.
D. An abstract interface.
✔ Correct Answer: Option B
Detailed Explanation: Just as an object is an instance of a class, a class in Python is an instance of a metaclass. The default metaclass is ‘type’. Custom metaclasses inherit from ‘type’ and intercept class creation (e.g., in ORMs and schema validators).
🎯 Key Learning Point: Tim Peters famously said: ‘Metaclasses are deeper magic than 99% of users should ever worry about.’
Question 56 of 75 Chapter 4
Which module in Python's standard library provides the '@dataclass' decorator (introduced in Python 3.7)?
A. types
B. dataclasses
C. models
D. collections
✔ Correct Answer: Option B
Detailed Explanation: The ‘dataclasses’ module provides the ‘@dataclass’ decorator, which automatically generates boilerplate special methods like ‘__init__’, ‘__repr__’, ‘__eq__’, and optional sorting methods based on type annotations.
🎯 Key Learning Point: Use ‘@dataclass(frozen=True)’ to create immutable, hashable value objects.
Question 57 of 75 Chapter 4
What magic method must be implemented to support the 'len(obj)' function on custom objects?
A. __size__
B. __length__
C. __len__
D. __count__
✔ Correct Answer: Option C
Detailed Explanation: The built-in ‘len()’ function delegates directly to the object’s ‘__len__()’ special method, which must return a non-negative integer.
🎯 Key Learning Point: If ‘__bool__’ is not defined, Python queries ‘__len__’ to determine truthiness (0 is False, >0 is True).
Question 58 of 75 Chapter 4
What is the purpose of 'abc.ABC' and '@abc.abstractmethod' in Python?
A. Compiling code to Abstract Binary Code.
B. Defining Abstract Base Classes (ABCs) that enforce that subclasses must implement specific abstract methods before they can be instantiated.
C. Creating alphabet string lists.
D. Speeding up class attribute lookups.
✔ Correct Answer: Option B
Detailed Explanation: Abstract Base Classes derived from ‘abc.ABC’ define formal interfaces. If a class contains an ‘@abstractmethod’, attempting to instantiate it or an incomplete subclass raises a TypeError: ‘Can’t instantiate abstract class with abstract method’.
🎯 Key Learning Point: ABCs provide formal interface verification at instantiation time.
Question 59 of 75 Chapter 4
What does '__getitem__' allow an object to do?
A. Delete an item.
B. Support square bracket indexing and slicing syntax (e.g. 'obj[key]' or 'obj[0]').
C. Add items to sets.
D. Convert to JSON.
✔ Correct Answer: Option B
Detailed Explanation: Implementing ‘__getitem__(self, key)’ enables subscript notation ‘obj[key]’. When sliced (‘obj[1:5]’), ‘key’ is passed as a ‘slice’ object.
🎯 Key Learning Point: Paired with ‘__setitem__’ and ‘__delitem__’, ‘__getitem__’ allows custom classes to emulate full Python sequence or mapping behavior.
Question 60 of 75 Chapter 4
What built-in function checks whether an object is an instance of a class or a tuple of classes?
A. type_check()
B. isinstance()
C. issubclass()
D. hasinstance()
✔ Correct Answer: Option B
Detailed Explanation: ‘isinstance(obj, class_or_tuple)’ checks whether obj is an instance of the class or any of its subclasses. It supports tuples: ‘isinstance(x, (int, float))’.
🎯 Key Learning Point: Prefer ‘isinstance(x, MyClass)’ over ‘type(x) == MyClass’ because isinstance respects inheritance.
Curriculum Track • Module 5 of 5
Chapter 5: Generators, Iterators, Exceptions & File I/O (Q61 – Q75)
Question 61 of 75 Chapter 5
What keyword transforms a regular Python function into a generator function?
A. return
B. yield
C. generate
D. emit
✔ Correct Answer: Option B
Detailed Explanation: The presence of the ‘yield’ statement converts a function into a generator factory. When called, it returns a generator iterator object without executing the body immediately, pausing and resuming state upon each iteration.
🎯 Key Learning Point: Generators maintain their execution state, local variables, and instruction pointer between successive yield statements.
Question 62 of 75 Chapter 5
What does 'yield from iterable' do in Python 3.3+?
A. Stops the generator.
B. Transparently delegates iteration to a sub-generator or iterable, forwarding values and bidirectional send/throw calls.
C. Copies all values into a list.
D. Re-raises exceptions.
✔ Correct Answer: Option B
Detailed Explanation: ‘yield from ‘ establishes a transparent bidirectional channel delegating iteration directly to a sub-generator, simplifying nested generators and coroutines without manual loops.
🎯 Key Learning Point: ‘yield from’ also captures the return value of the sub-generator: ‘val = yield from subgen()’.
Question 63 of 75 Chapter 5
What block is guaranteed to execute whether an exception is raised or not in a try-except structure?
A. else
B. finally
C. catch
D. retry
✔ Correct Answer: Option B
Detailed Explanation: The ‘finally’ clause is always executed prior to leaving the try-statement, regardless of whether exceptions were raised, caught, or suppressed, making it essential for resource cleanup (closing sockets, freeing handles).
🎯 Key Learning Point: The ‘else’ clause executes ONLY if NO exception was raised in the try block.
Question 64 of 75 Chapter 5
What is the recommended modern mode to open files for automatic cleanup in Python?
A. Using the 'with open(filename) as f:' context manager.
B. Calling open() and relying on garbage collection.
C. Calling file.close() inside a thread.
D. Using sys.open().
✔ Correct Answer: Option A
Detailed Explanation: The ‘with open(…) as f:’ context manager guarantees that the underlying OS file descriptor is flushed and closed immediately when execution exits the block, even if an unhandled exception or return occurs.
🎯 Key Learning Point: Always specify explicit encoding: ‘with open(fn, ‘r’, encoding=’utf-8′) as f:’ to prevent platform-dependent decoding bugs.
Question 65 of 75 Chapter 5
What is Exception Chaining in Python 3, using 'raise NewException from OriginalException'?
A. Raising exceptions in multiple threads.
B. Explicitly attaching the original exception as the '__cause__' attribute of the new exception, preserving full root-cause debugging traces.
C. Suppressing the original exception.
D. Creating infinite exception loops.
✔ Correct Answer: Option B
Detailed Explanation: ‘raise NewException from OriginalException’ explicitly chains the cause. The traceback clearly outputs ‘The above exception was the direct cause of the following exception:’ preserving the full diagnostic path.
🎯 Key Learning Point: Use ‘raise NewException from None’ to intentionally suppress display of previous internal exception traces.
Question 66 of 75 Chapter 5
What does calling 'next(iterator, default)' do when the iterator is exhausted?
A. Raises StopIteration.
B. Returns the provided fallback 'default' value cleanly without raising StopIteration.
C. Restarts the iterator from the beginning.
D. Truncates memory.
✔ Correct Answer: Option B
Detailed Explanation: ‘next(it, default)’ retrieves the next item. If the iterator raises StopIteration and a default argument is provided, next() catches it and returns the default value safely.
🎯 Key Learning Point: Using ‘next(it, None)’ avoids messy try-except StopIteration blocks.
Question 67 of 75 Chapter 5
What is the purpose of the 'sys.intern()' function in Python?
A. Submits code to an internship portal.
B. Enters a string into Python's global internal table of interned strings, ensuring only one instance exists in memory and allowing pointer-speed comparisons with 'is'.
C. Deletes temporary files.
D. Encrypts strings.
✔ Correct Answer: Option B
Detailed Explanation: String interning ensures that strings with identical values share a single memory address. When interned, checking string equality reduces from an O(N) byte comparison to an O(1) pointer comparison.
🎯 Key Learning Point: Python automatically interns identifiers (like variable names and dictionary keys) to optimize attribute and key lookups.
Question 68 of 75 Chapter 5
Which module provides high-level object serialization into binary streams in Python?
A. json
B. pickle
C. marshal
D. csv
✔ Correct Answer: Option B
Detailed Explanation: The ‘pickle’ module serializes nearly arbitrary Python object graphs into byte streams. (Caution: pickle is not secure against erroneous or maliciously constructed data; never unpickle untrusted data).
🎯 Key Learning Point: Use JSON for cross-language, human-readable data; reserve pickle for internal Python-only state persistence.
Question 69 of 75 Chapter 5
What method on a generator object allows sending a value back into the generator where it was paused at a yield expression?
A. push()
B. send()
C. inject()
D. resume()
✔ Correct Answer: Option B
Detailed Explanation: Calling ‘generator.send(value)’ resumes the generator and causes the current ‘yield’ expression to evaluate to the received value, enabling coroutine communication.
🎯 Key Learning Point: A newly created generator must be primed (by calling ‘next(gen)’ or ‘gen.send(None)’) before sending non-None values.
Question 70 of 75 Chapter 5
What is the difference between 'read()', 'readline()', and 'readlines()' on file objects?
A. read() reads whole file as a string; readline() reads one line; readlines() reads all lines into a list of strings.
B. They are exact aliases.
C. read() works only on binary files.
D. readlines() deletes the file.
✔ Correct Answer: Option A
Detailed Explanation: ‘f.read()’ loads the entire file content into a single string. ‘f.readline()’ reads characters until the next newline. ‘f.readlines()’ reads all remaining lines into a list of strings.
🎯 Key Learning Point: For large files, avoid readlines(); iterate directly over the file object (‘for line in f:’) to stream line by line in O(1) memory.
Question 71 of 75 Chapter 5
What built-in exception is raised when an imported module or from-import name cannot be found?
A. FileNotFoundError
B. ModuleNotFoundError (subclass of ImportError)
C. NameError
D. AttributeError
✔ Correct Answer: Option B
Detailed Explanation: Python 3.6 introduced ‘ModuleNotFoundError’ (which inherits from ‘ImportError’) specifically raised when an import statement fails to find the specified module.
🎯 Key Learning Point: Catch ‘ModuleNotFoundError’ when attempting optional feature imports (e.g. ‘try: import ujson except ModuleNotFoundError: import json’).
Question 72 of 75 Chapter 5
What is the Global Interpreter Lock (GIL) in standard CPython?
A. A hardware mutex on the motherboard.
B. A mutex lock that prevents multiple native OS threads from executing CPython bytecodes simultaneously in the same process.
C. A file locking mechanism.
D. A database security mechanism.
✔ Correct Answer: Option B
Detailed Explanation: The GIL is a mutual-exclusion lock used by CPython to ensure thread-safe memory management (protecting reference counts). Consequently, CPU-bound multi-threaded Python programs do not achieve true multi-core speedup on CPython.
🎯 Key Learning Point: To achieve true parallel CPU execution in Python, use the ‘multiprocessing’ module or free-threaded Python (PEP 703).
Question 73 of 75 Chapter 5
What is the purpose of 'weakref' in Python?
A. Creating fragile variables.
B. Creating weak references to objects that allow referencing an object without increasing its reference count, preventing circular reference memory leaks.
C. Speeding up string searches.
D. Weak password hashing.
✔ Correct Answer: Option B
Detailed Explanation: A weak reference (‘weakref’) does not increment the target object’s reference count. If only weak references remain, the garbage collector frees the object, preventing circular memory retention in caches and observers.
🎯 Key Learning Point: ‘weakref.ref(obj)’ returns a callable that yields the target object if alive, or None if it has been collected.
Question 74 of 75 Chapter 5
What does the 'os.scandir()' function provide over 'os.listdir()' in file system traversal?
A. It deletes invalid directories.
B. It returns an iterator of DirEntry objects that include file attribute information (like is_dir() and stat()), dramatically speeding up directory scans by eliminating extra stat() system calls.
C. It works only on Windows.
D. It searches hidden files.
✔ Correct Answer: Option B
Detailed Explanation: ‘os.scandir()’ leverages the directory entry information provided natively by the operating system during directory iteration, making file tree scans 2x to 20x faster than ‘os.listdir()’.
🎯 Key Learning Point: Use ‘os.scandir()’ or ‘pathlib.Path.iterdir()’ for high-performance filesystem exploration.
Question 75 of 75 Chapter 5
What will be printed when running this generator?

def countdown(n):
while n > 0:
yield n
n -= 1

print(list(countdown(3)))
def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))
A. [3, 2, 1]
B. [3, 2, 1, 0]
C. [1, 2, 3]
D. 3
✔ Correct Answer: Option A
Detailed Explanation: The generator yields 3 (n becomes 2), yields 2 (n becomes 1), yields 1 (n becomes 0). The while loop condition (0 > 0) is false, terminating iteration. ‘list()’ collects the yielded items into [3, 2, 1].
🎯 Key Learning Point: Generators compute elements on-demand, consuming O(1) auxiliary memory regardless of sequence length.

Explore Other Comprehensive 75-Question Subject Tracks

Continue your preparation across our active curriculum tracks. Every track provides 75 verified questions across 5 complete chapters.

🟢 100% Live Track
C Programming
75 Qs • 5 Chapters • Practice Now →
Active Track
📍 Python Programming
75 Qs • 5 Chapters (You are here)
🟢 100% Live Track
Data Structures
75 Qs • 5 Chapters • Practice Now →
🟢 100% Live Track
DBMS & SQL
75 Qs • 5 Chapters • Practice Now →
🟢 100% Live Track
Computer Networks
75 Qs • 5 Chapters • Practice Now →
🟢 100% Live Track
Operating Systems
75 Qs • 5 Chapters • Practice Now →
🟢 100% Live Track
Quantitative Aptitude
75 Qs • 5 Chapters • Practice Now →
📚 View All 92+ Subjects in Master Directory
Share
  • Facebook
Queryiest

Queryiest

Enlightened

Queryiest – Technology Writer | Software Developer | Digital Learning Enthusiast

Queryiest is a technology writer, software developer, and knowledge-sharing enthusiast passionate about simplifying complex technical concepts for students, professionals, and lifelong learners. With expertise in software development, programming, cybersecurity, artificial intelligence, digital tools, and emerging technologies, Queryiest creates practical, research-driven content that helps readers solve real-world problems. As a regular contributor to RTSALL, Queryiest publishes easy-to-understand guides, coding resources, technology news, career advice, and educational tutorials designed for beginners and professionals alike. Every article focuses on accuracy, clarity, and actionable insights to help readers stay informed in the rapidly evolving digital world. Whether it's programming, software engineering, AI, cybersecurity, online platforms, or digital productivity, Queryiest believes that quality knowledge should be accessible to everyone. The goal is to build a trusted learning resource where readers can discover reliable answers, improve their technical skills, and make informed decisions. Areas of Expertise: Software Development, Programming, Cybersecurity, Artificial Intelligence, Technology News, Coding Interview Preparation, Digital Learning, Productivity Tools, and Online Knowledge Sharing.

    Sidebar

    Ask A Question
    • Popular
    • Answers
    • Queryiest

      What is a database?

      • 3 Answers
    • Anonymous

      How to rotate an array in-place with O(1) space and ...

      • 3 Answers
    • hannah

      What steps can businesses take to identify the most valuable ...

      • 2 Answers
    • Vikram
      aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
    • Abhishek
      Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
    • Sneha Patel
      Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

    Top Members

    Queryiest

    Queryiest

    • 201 Questions
    • 295 Points
    Enlightened
    Anonymous

    Anonymous

    • 11 Questions
    • 42 Points
    Begginer
    paperubofficial

    paperubofficial

    • 0 Questions
    • 22 Points
    Begginer

    Trending Tags

    ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

    Explore

    • Home
    • Add group
    • Groups page
    • Communities
    • Questions
      • DSA Problems
    • Polls
    • Tags
    • Badges
    • Users
    • Help
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions

    Footer

    About Us

    • Meet The Team
    • Blog
    • About Us
    • Contact Us

    Legal Stuff

    • Privacy Policy
    • Disclaimer
    • Terms & Conditions

    Help

    • Knowledge Base
    • Support

    Follow

    © 2023-25 RTSALL. All Rights Reserved