Python Basics
1. What are Python's key features?
- Easy to learn and read.
- Interpreted and dynamically typed.
- Supports multiple programming paradigms (OOP, functional, procedural).
- Has a large standard library.
- Extensible and embeddable.
2. What is the difference between Python 2 and Python 3?
- Python 2 is outdated and no longer maintained.
- Python 3 uses print() as a function (print "Hello" → print("Hello")).
- Unicode handling is better in Python 3 (str is Unicode by default).
- Division behavior changed (5/2 → 2.5 instead of 2).
3. How does Python handle memory management?
- Uses Garbage Collection (GC) to reclaim unused memory.
- Uses Reference Counting to track objects.
- Uses a private heap for storing objects.
4. What is PEP 8, and why is it important?
- PEP 8 is the Python style guide that helps make code readable and consistent.
- It covers naming conventions, indentation, whitespace, and more.
5. Explain Python's data types.
- int: Whole numbers (e.g., 10, -5, 1000).
- float: Decimal numbers (e.g., 3.14, -2.5).
- list: Ordered, mutable collection (e.g., [1, 2, 3]).
- tuple: Ordered, immutable collection (e.g., (1, 2, 3)).
- dict: Key-value pairs (e.g., {"name": "Alice", "age": 25}).
- set: Unordered collection of unique items (e.g., {1, 2, 3}).
6. What is the difference between a list and a tuple?
- List is mutable ([1, 2, 3] → list[0] = 10).
- Tuple is immutable ((1, 2, 3) → Cannot modify elements).
- Tuples are faster than lists for fixed data.
7. How do you handle exceptions in Python? Give an example.
Use try-except to catch errors.
Python
Copy
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
8. Explain the use of the with statement in Python.
Used for resource management (e.g., file handling).
Python
Copy
with open("file.txt", "r") as file: content = file.read() # File automatically closes after this block.
9. What is the difference between is and == operators?
- is: Checks if two variables point to the same object in memory.
- ==: Checks if values are equal.
Python
Copy
a = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) # True (same object) print(a == c) # True (same values) print(a is c) # False (different objects)
10. How does Python handle mutability?
- Mutable objects: Can be changed (list, dict, set).
- Immutable objects: Cannot be changed (int, float, tuple, string).
11. Explain the difference between deepcopy() and copy().
- copy.copy() : Creates a shallow copy (nested objects remain shared).
- copy.deepcopy() : Creates a deep copy (fully independent copy).
Python
Copy
import copy a = [[1, 2], [3, 4]] b = copy.copy(a) # Shallow copy c = copy.deepcopy(a) # Deep copy
12. What is the difference between append() and extend() in lists?
- append(): Adds a single element.
- extend(): Adds multiple elements from an iterable.
Python
Copy
lst = [1, 2, 3] lst.append([4, 5]) # [1, 2, 3, [4, 5]] lst.extend([4, 5]) # [1, 2, 3, 4, 5]
13. How do you remove duplicates from a list?
Python
Copy
lst = [1, 2, 2, 3, 4, 4, 5] unique_lst = list(set(lst)) # {1, 2, 3, 4, 5}
14. What are *args and **kwargs in Python functions?
- *args: Passes multiple positional arguments.
- **kwargs: Passes multiple keyword arguments.
Python
Copy
def example(*args, **kwargs): print(args, kwargs) example(1, 2, 3, name="Alice", age=25) # Output: (1, 2, 3) {'name': 'Alice', 'age': 25}
15. Explain the difference between a shallow copy and a deep copy.
- Shallow Copy: Copies references (changes affect both copies).
- Deep Copy: Creates a completely independent copy.
16. How do you swap two variables in Python without using a temporary variable?
Python
Copy
a, b = 10, 20 a, b = b, a print(a, b) # 20, 10
17. What is the difference between global, nonlocal, and local variables?
- local: Defined inside a function.
- global: Declared outside functions, accessible everywhere.
- nonlocal: Used inside nested functions to modify variables from the outer function.
18. Explain list comprehension with an example.
Python
Copy
numbers = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
19. How do you reverse a string in Python?
text = "Python" print(text[::-1]) # "nohtyP"
20. How do you read and write files in Python?
Python
Copy
# Writing to a file with open("example.txt", "w") as f: f.write("Hello, Python!") # Reading from a file with open("example.txt", "r") as f: content = f.read() print(content) # "Hello, Python!"