1. Python Fundamentals
Q1: What is the difference between Mutable and Immutable objects in Python?
- Mutable: Objects whose state or contents can be modified in-place after creation without changing their memory ID (
list,dict,set,bytearray). - Immutable: Objects whose state cannot be changed once allocated. Modifying them creates a new object in memory (
int,float,string,tuple,frozenset).
Q2: What is the Python GIL (Global Interpreter Lock)?
Answer: The GIL is a mutex (or lock) that allows only one native thread to execute Python bytecode at a time in CPython. This ensures thread safety in memory management. For CPU-bound tasks, developers use the multiprocessing module instead of threading to leverage multiple CPU cores.
2. Lists vs Tuples vs Sets vs Dictionaries
3. Decorators and Generators
Q3: What is a Decorator and where is it used?
A decorator is a design pattern in Python that allows you to add new functionality to an existing function or method without modifying its structure.
Q4: What is the difference between `return` and `yield`?
returnterminates the function and returns a single value back to the caller.yieldturns the function into a Generator. It pauses function execution, saves its state, and yields an item one at a time on-demand, saving immense memory when handling huge datasets.
4. *args, **kwargs and Scope Resolution (LEGB)
Q5: What is the purpose of `*args` and `**kwargs`?
*argsallows you to pass a variable number of non-keyword positional arguments to a function as a tuple.kwargsallows you to pass a variable number of keyword arguments to a function as a dictionary**.
Q6: How does Python resolve variable scope (LEGB Rule)?
Python searches for variable names in the following exact sequence:
- L (Local): Defined inside the current function.
- E (Enclosing): Defined in the outer enclosing scope of nested functions.
- G (Global): Defined at the top level of the module/script.
- B (Built-in): Reserved built-in names (
len,range,print,open).