1. What is the difference between a list and a tuple?
Answer:
- Mutability: Lists are mutable (can be changed), tuples are immutable (cannot be changed).
- Syntax: Lists use
[], tuples use(). - Performance: Tuples are slightly faster and consume less memory.
- Use Case: Use lists for collections that change; use tuples for fixed data records.
2. Explain `*args` and `**kwargs`.
Answer:
*argsallows passing a variable number of positional arguments (received as a tuple).**kwargsallows passing a variable number of keyword arguments (received as a dictionary).
def func(*args, **kwargs):
print(args) # (1, 2)
print(kwargs) # {'a': 3}
func(1, 2, a=3)
3. How does Python handle memory management?
Answer: Python uses a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager.
- Reference Counting: The primary mechanism. When an object's reference count drops to zero, it is deallocated.
- Garbage Collector: A cyclic garbage collector handles reference cycles that reference counting cannot catch.
4. What are Python decorators?
Answer: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. It is usually a function that takes another function as an argument and extends its behavior.
5. What are Generators and the `yield` keyword?
Answer: Generators are functions that return an iterable set of items, one at a time, in a special way.
- When an iteration over a set of items starts using the
forstatement, the generator is run. - Once the generator's function code reaches a
yieldstatement, the generator yields its execution back to the for loop, returning a new value from the set. - Benefit: Memory efficient. It doesn't store the whole list in memory.
6. Explain Context Managers (`with` statement).
Answer: Context managers allow you to allocate and release resources precisely when you want to. The most widely used example is the with statement.
with open('file.txt', 'w') as f:
f.write('hello')
It ensures that the file is closed automatically, even if an exception occurs. It uses the __enter__ and __exit__ magic methods.
7. What is the difference between `is` and `==`?
Answer:
==checks for value equality. (Do these two objects contain the same data?)ischecks for reference equality. (Do these two variables point to the exact same object in memory?)