Python Interview Questions (Fundamentals)
A comprehensive guide to Python interview questions, organized by category. This collection covers fundamental syntax to advanced concepts for the 2025 edition.1. Python Basics
1. What is Python and what are its key features?
1. What is Python and what are its key features?
- Easy to Learn/Read: Simple syntax that resembles English.
- Interpreted: Code is executed line-by-line, no separate compilation needed.
- Dynamically Typed: Variable types are determined at runtime.
- Object-Oriented: Supports classes and object encapsulation.
- Extensive Libraries: Massive standard library for almost any task.
- Cross-platform: Runs on Windows, Linux, and macOS.
2. What are Python's built-in data types?
2. What are Python's built-in data types?
| Category | Types |
|---|---|
| Numeric | int, float, complex |
| Sequence | list, tuple, range, str |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool |
| None Type | NoneType |
3. What is the difference between lists and tuples?
3. What is the difference between lists and tuples?
| Feature | Lists | Tuples |
|---|---|---|
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Syntax | Square brackets [] | Parentheses () |
| Performance | Slower | Faster |
| Methods | Many built-in methods | Fewer methods |
| Use Case | Frequent modifications | Fixed data / Constants |
4. Explain Python's mutable and immutable types.
4. Explain Python's mutable and immutable types.
- Mutable: Objects that can be modified after creation.
- Examples:
list,dict,set, and custom class objects. - Example:
l = [1]; l[0] = 2(Works)
- Examples:
- Immutable: Objects that cannot be changed once created. Any modification creates a new object.
- Examples:
int,float,str,tuple,frozenset. - Example:
s = 'hi'; s[0] = 'H'(RaisesTypeError)
- Examples:
5. Identity Operators: 'is' vs 'is not'
5. Identity Operators: 'is' vs 'is not'
6. Python Naming Conventions (PEP 8)
6. Python Naming Conventions (PEP 8)
- Variables/Functions:
snake_case(e.g.,calculate_sum). - Classes:
PascalCase(e.g.,MyClass). - Constants:
UPPER_CASE(e.g.,MAX_RETRIES). - Private Variables: Single underscore prefix (
_private). - Avoid: Single letters except for loops (
i, j, k).
7. Equality (==) vs Identity (is) operators
7. Equality (==) vs Identity (is) operators
==checks for Equality (Do they have the same value?).ischecks for Identity (Do they point to the exact same memory address?).
None checks: if val is None:.8. Membership Operators: 'in' vs 'not in'
8. Membership Operators: 'in' vs 'not in'
2. Data Structures
9. List Manipulation Methods
9. List Manipulation Methods
list:append(x): Addsxto the end.insert(i, x): Insertsxat indexi.remove(x): Removes the first occurrence ofx.pop(): Removes and returns the last element.extend(iter): Adds all elements from an iterable.sort(): Sorts the list in place.
10. List Comprehensions
10. List Comprehensions
[expression for item in iterable if condition]11. Dictionaries and Key Methods
11. Dictionaries and Key Methods
get(key, default): Safely access values without raising errors.keys()/values()/items(): Views of the dictionary components.update(other_dict): Merge another dictionary into the current one.
12. Sets vs Frozensets
12. Sets vs Frozensets
- Set: Mutable, unordered collection of unique elements. Supports
add()andremove(). - Frozenset: Immutable version of a set. Can be used as a dictionary key or an element of another set.
13. Set Operations
13. Set Operations
| Operation | Operator | Method | |
|---|---|---|---|
| Union | ` | ` | set1.union(set2) |
| Intersection | & | set1.intersection(set2) | |
| Difference | - | set1.difference(set2) | |
| Sym. Diff | ^ | set1.symmetric_difference(set2) |
14. Sequence Operations (Slicing/Indexing)
14. Sequence Operations (Slicing/Indexing)
text[0]: Access first element.text[1:4]: Slice from index 1 to 3.text[::-1]: Reverse the sequence.len(text): Get length.
15. How do you sort a list of dictionaries?
15. How do you sort a list of dictionaries?
sorted() function with a lambda as the key parameter.16. Deep Copy vs Shallow Copy
16. Deep Copy vs Shallow Copy
- Shallow Copy: Creates a new container, but elements inside still refer to the original objects.
- Deep Copy: Creates a new container and recursively copies every object inside it (completely independent).
3. Object-Oriented Programming
17. Four Pillars of OOP
17. Four Pillars of OOP
- Encapsulation: Bundling data and methods, hiding internal state.
- Abstraction: Hiding complexity and showing only necessary features.
- Inheritance: Creating new classes based on existing ones.
- Polymorphism: Ability for different objects to respond to the same method call differently.
18. Creating a Class and __init__
18. Creating a Class and __init__
19. Instance vs Class vs Static Methods
19. Instance vs Class vs Static Methods
- Instance: Accesses
self. Standard method. - Class: Accesses
cls. Decorated with@classmethod. Operates on class state. - Static: No access to
selforcls. Decorated with@staticmethod. Just a utility function.
20. Inheritance and super()
20. Inheritance and super()
super() is used to call methods (usually the constructor) from the parent class.21. Magic Methods (Dunder Methods)
21. Magic Methods (Dunder Methods)
__.__init__: Constructor.__str__: Human-readable string representation.__repr__: Detailed developers representation.__len__: Custom length logic.__add__: Operator overloading for+.
22. Property Decorators (@property)
22. Property Decorators (@property)
4. Functions and Decorators
25. What are *args and **kwargs?
25. What are *args and **kwargs?
*args: Accepts a variable number of positional arguments (as a tuple).**kwargs: Accepts a variable number of keyword arguments (as a dictionary).
26. Lambda Functions
26. Lambda Functions
square = lambda x: x * x27. What are Decorators?
27. What are Decorators?
28. Closures
28. Closures
31. Generators and yield
31. Generators and yield
yield. They are memory efficient because they don’t store the whole sequence in RAM.5. File Handling and I/O
33. How do you read and write files?
33. How do you read and write files?
with statement (context manager) to ensure files are closed properly.36. Working with JSON
36. Working with JSON
6. Exception Handling
39. try-except Blocks
39. try-except Blocks
41. try-except-else-finally
41. try-except-else-finally
else: Runs if NO exception occurred.finally: ALWAYS runs (cleanup code).
8. Advanced Concepts
51. Iterators vs Iterables
51. Iterators vs Iterables
- Iterable: Any object you can loop over (List, Tuple). Implements
__iter__. - Iterator: The actual object that tracks state during iteration. Implements
__next__.
52. Multithreading vs Multiprocessing
52. Multithreading vs Multiprocessing
- Multithreading: Shares memory. Best for I/O-bound tasks. Subject to the GIL.
- Multiprocessing: Separate memory space. Best for CPU-bound tasks. True parallelism.
53. Global Interpreter Lock (GIL)
53. Global Interpreter Lock (GIL)
10. Data Science & Numerical Python
65. What is NumPy?
65. What is NumPy?
ndarray, which is faster and more memory-efficient than Python lists for mathematical operations.66. What is Pandas?
66. What is Pandas?
Series (1D) and DataFrame (2D table).Additional Important Topics
76. enumerate() vs zip()
76. enumerate() vs zip()
enumerate(iterable): Adds a counter (index) to an iterable.zip(*iterables): Aggregates elements from multiple iterables into tuples.
86. range() function
86. range() function
100. PEP 8
100. PEP 8
- Use 4 spaces for indentation.
- Limit lines to 79 characters.
- Use blank lines to separate functions/classes.
- Imports should be at the top.