Test your fundamental knowledge of Python interview concepts with this easy multiple-choice quiz. Cover key topics including data structures, memory management, decorators, Pythonic code, and exception handling for effective technical preparation.
Which of the following is a key difference between lists, tuples, and sets in Python?
Explanation: Lists are mutable, meaning their items can be changed. Tuples are immutable, so their values cannot be altered after creation. Sets are unordered collections and do not allow duplicate elements. The other options either misstate the mutability or ordering of these data structures, or incorrectly describe which types allow duplicates.
In Python, what is the main difference between a shallow copy and a deep copy of an object?
Explanation: A shallow copy creates a new collection but inserts references into the original objects, while a deep copy recursively copies all objects, including nested ones. Removing duplicates and inverting data have nothing to do with copying mechanisms. The statement saying a deep copy only copies the top level is incorrect; that's what a shallow copy does.
What does Python’s Global Interpreter Lock (GIL) do in the context of multi-threaded programs?
Explanation: The GIL ensures that only one thread executes Python bytecode at any given moment, limiting the effectiveness of multi-threaded CPU-bound programs in Python. It does not prevent object creation or disable threading. The third option is incorrect; the GIL actually prevents parallel execution of multiple threads on multiple CPUs.
When would you typically use a decorator in Python?
Explanation: Decorators provide a way to add functionality to existing functions or methods in a reusable way. They do not handle encryption or global variable initialization, nor are they used to create data types. The primary purpose of decorators is to wrap functions for enhanced or altered behavior.
Which statement correctly describes Python’s memory management?
Explanation: Python automatically manages memory using a garbage collector, which reclaims memory from objects that are no longer in use. Manual memory management is not required, unlike in some other languages. The third and fourth options are incorrect, as the garbage collector handles all objects, not just lists.
What is a key difference between @staticmethod and @classmethod in Python?
Explanation: A staticmethod behaves like a regular function but belongs to a class, and does not receive self or cls. A classmethod receives the class as its first parameter, typically named cls. The other statements are incorrect because staticmethods do not require instance variables or the self parameter, and classmethods are for class-level operations, not global functions.
How does Python’s garbage collection mechanism identify which objects to reclaim?
Explanation: Python’s garbage collection primarily uses reference counting, and also detects reference cycles that cannot be collected by reference counting alone. It does not rely on the programmer for manual deallocation. Ending a function only removes local references but does not guarantee garbage collection. Syntax errors are unrelated to memory management.
What is a key difference between threading and multiprocessing in Python?
Explanation: Threading allows for concurrent tasks within one process and shared memory, while multiprocessing involves separate processes that do not share memory space. Multiprocessing can bypass the GIL limitation, unlike threading. Neither threading nor multiprocessing is inherently faster in all cases, and both are supported on major operating systems.
What does it mean for code to be described as ‘Pythonic’?
Explanation: Pythonic code emphasizes readability, simplicity, and use of established Python conventions. Execution speed is not the primary concern. Using only uppercase variable names does not make code Pythonic, and avoiding functions goes against good coding practices.
How does Python's exception hierarchy help with error handling?
Explanation: The exception hierarchy lets programmers catch errors that are specific or general by catching parent or child exception classes. It does not prevent exceptions, nor does it limit handling to the top level or support only a single exception type. This design makes handling different errors flexible and maintainable.
Which of the following is an example of an immutable built-in type in Python?
Explanation: A tuple is an immutable sequence in Python, meaning its values cannot be changed after creation. Lists, dictionaries, and sets are all mutable because their content can be altered during the program's execution. Understanding which types are mutable is essential when handling shared or cached data.
Which method in Python allows formatted insertion of variables into strings, such as 'Hello, {}.format(name)'?
Explanation: The str.format() method allows variables to be inserted into a string using placeholders. str.change(), str.insert(), and str.update() are not valid methods for string formatting in Python. Knowing how to format strings is useful for producing clear output.
Which keyword should you use to automatically close files after reading or writing in Python?
Explanation: The with statement ensures that a file is properly closed after its suite finishes, even if exceptions occur. The open keyword is used to open a file but does not itself manage closing. The try block can help with error handling but does not automatically close files unless combined with with. The close method must be called manually.
What happens if you modify a mutable default argument like a list in a Python function?
Explanation: Mutable default arguments like lists or dictionaries are only created once when the function is defined, so changes persist across calls. Each call does not get a fresh list unless specified inside the function. There is no automatic reset or error raised; if this behavior is undesired, use immutable defaults or set defaults inside the function.
What is the output type of a basic list comprehension such as [x for x in range(3)]?
Explanation: A list comprehension constructs and returns a list based on the specified expression and sequence. Tuples, sets, and strings require their own specific comprehension syntaxes or functions. Knowing the difference is important to avoid confusion in code.
What is the result of the Python expression 'bool([])'?
Explanation: In Python, empty containers like lists, tuples, sets, and dictionaries evaluate to False in boolean contexts. Non-empty ones are True. None is a different singleton object, and evaluating 'bool([])' does not cause any error. This is useful for simple testing of empty collections.