Python Interview Essentials Quiz Quiz

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.

  1. Lists, Tuples, and Sets

    Which of the following is a key difference between lists, tuples, and sets in Python?

    1. Lists are mutable, tuples are immutable, and sets are unordered collections.
    2. Lists and tuples are both unordered, while sets are ordered.
    3. Tuples and sets allow duplicates, but lists do not.
    4. Lists are immutable, tuples are mutable, and sets do not allow duplicates.

    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.

  2. Deep Copy vs Shallow Copy

    In Python, what is the main difference between a shallow copy and a deep copy of an object?

    1. A deep copy only copies the top level, but leaves nested objects shared.
    2. A shallow copy inverts data; a deep copy does not.
    3. A shallow copy automatically removes duplicates; a deep copy does not.
    4. A shallow copy only copies references to objects; a deep copy copies objects recursively.

    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.

  3. Global Interpreter Lock (GIL)

    What does Python’s Global Interpreter Lock (GIL) do in the context of multi-threaded programs?

    1. It disables all threading features by default.
    2. It prevents new objects from being created in threads.
    3. It allows multiple threads to run in parallel on multiple CPUs.
    4. It allows only one thread to execute Python bytecode at a time.

    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.

  4. Decorators Usage

    When would you typically use a decorator in Python?

    1. To create a new data type.
    2. To encrypt variable values before use.
    3. To initialize global variables.
    4. To modify or extend the behavior of a function without changing its code.

    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.

  5. Memory Management

    Which statement correctly describes Python’s memory management?

    1. Developers must manually allocate and free memory for every variable.
    2. Only lists are managed automatically; other objects must be deleted by the user.
    3. Python provides no mechanism for garbage collection.
    4. Python uses automatic memory management with a built-in garbage collector.

    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.

  6. Staticmethod vs Classmethod

    What is a key difference between @staticmethod and @classmethod in Python?

    1. @classmethod can only be used with global functions.
    2. @staticmethod does not receive an implicit first argument; @classmethod receives the class as its first argument.
    3. @staticmethod must always access instance variables.
    4. @staticmethod and @classmethod both require the self parameter.

    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.

  7. Garbage Collection

    How does Python’s garbage collection mechanism identify which objects to reclaim?

    1. By using reference counting and detecting unreachable objects in cycles.
    2. By requiring the programmer to free every object manually.
    3. By deleting all variables when a function ends.
    4. By checking for syntax errors in code.

    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.

  8. Threading vs Multiprocessing

    What is a key difference between threading and multiprocessing in Python?

    1. Threading requires a special operating system version, but multiprocessing does not.
    2. Threading always runs faster than multiprocessing.
    3. Multiprocessing is limited by the Global Interpreter Lock, while threading is not.
    4. Threading uses multiple threads within a process; multiprocessing uses multiple processes with separate memory.

    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.

  9. Pythonic Code

    What does it mean for code to be described as ‘Pythonic’?

    1. It is written using only uppercase variable names.
    2. It is written in a way that follows Python’s idioms and best practices for readability and simplicity.
    3. It always runs the fastest.
    4. It avoids using functions entirely.

    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.

  10. Exception Hierarchy

    How does Python's exception hierarchy help with error handling?

    1. It prevents any exceptions from being raised.
    2. It forces all exceptions to be handled at the top level only.
    3. It organizes exceptions so that errors can be caught broadly or specifically.
    4. It only supports one type of exception.

    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.

  11. Mutable vs Immutable Types

    Which of the following is an example of an immutable built-in type in Python?

    1. List
    2. Set
    3. Tuple
    4. Dictionary

    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.

  12. String Formatting

    Which method in Python allows formatted insertion of variables into strings, such as 'Hello, {}.format(name)'?

    1. str.insert()
    2. str.change()
    3. str.format()
    4. str.update()

    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.

  13. File Handling

    Which keyword should you use to automatically close files after reading or writing in Python?

    1. with
    2. open
    3. try
    4. close

    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.

  14. Default Arguments

    What happens if you modify a mutable default argument like a list in a Python function?

    1. The modified list persists across function calls.
    2. The list gets automatically reset after each use.
    3. It raises an error every time.
    4. Each call gets a new empty list automatically.

    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.

  15. Comprehensions

    What is the output type of a basic list comprehension such as [x for x in range(3)]?

    1. Tuple
    2. String
    3. Set
    4. List

    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.

  16. Boolean Expressions

    What is the result of the Python expression 'bool([])'?

    1. True
    2. None
    3. False
    4. Error

    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.