Python Interview Preparation 🎯
Ace your Python interview with this curated collection of questions, answers, coding challenges, and expert tips. Covers beginner, intermediate, and advanced topics.
Interview Topics Mind Map​
🟢 Beginner Questions​
1. What is Python? What are its key features?​
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. Key features include:
- Easy to read: Clean syntax with English-like keywords
- Interpreted: Code runs line by line without compilation
- Dynamically typed: No need to declare variable types
- Object-oriented: Supports classes, inheritance, and polymorphism
- Extensive standard library: "Batteries included" philosophy
- Cross-platform: Runs on Windows, macOS, Linux, and more
See What is Python? and Features & Applications.
2. How is Python an interpreted language?​
Python source code is compiled to bytecode (.pyc files) by the interpreter, which is then executed by the Python Virtual Machine (PVM). This happens automatically, so developers see it as "interpreted." Unlike C or Java, there is no separate compilation step before running.
See What is Python?.
3. What are mutable and immutable data types? Give examples.​
- Mutable: Objects that can be changed after creation. Examples:
list,dict,set,bytearray. - Immutable: Objects that cannot be changed after creation. Examples:
int,float,str,tuple,frozenset,bool.
# Mutable
my_list = [1, 2, 3]
my_list.append(4) # Works fine
# Immutable
my_tuple = (1, 2, 3)
# my_tuple[0] = 99 # TypeError!
4. What is the difference between a list and a tuple?​
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable | Immutable |
| Performance | Slower | Faster |
| Memory | Larger | Smaller |
| Use case | Dynamic data | Fixed data |
| Dict key | No | Yes (if hashable) |
5. What is __init__?​
__init__ is a special method (constructor) in Python classes. It is automatically called when a new object is created. It initializes the object's attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 25) # __init__ called automatically
See Constructors.
6. What is self?​
self is a reference to the current instance of a class. It is the first parameter of instance methods and is used to access attributes and methods of the class. The name self is a convention, not a keyword.
See Classes & Objects.
7. What is PEP 8?​
PEP 8 (Python Enhancement Proposal 8) is Python's style guide. It recommends conventions for naming, indentation, line length, imports, and whitespace to make Python code consistent and readable. Key rules: 4 spaces per indentation level, 79 characters per line, snake_case for variables/functions, UPPER_CASE for constants.
See Syntax & Comments.
8. What are comments in Python?​
Comments are lines ignored by the interpreter, used to explain code. Python uses # for single-line comments. Multi-line comments use # on each line or triple-quoted strings (which are technically docstrings).
# This is a single-line comment
x = 5 # Inline comment
"""
This is a multi-line string
(used as a comment)
"""
9. What is type() used for?​
type() returns the type of an object. It is used for checking or debugging data types.
print(type(5)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type([1, 2])) # <class 'list'>
10. What is None?​
None is a special constant in Python representing the absence of a value. It is of type NoneType. Functions without a return statement return None by default. It is not the same as 0, False, or an empty string.
result = print("hi") # print() returns None
print(result is None) # True
11. What is a docstring?​
A docstring is a string literal that documents a function, class, or module. It appears as the first statement in the definition and is enclosed in triple quotes. Accessible via help() or .__doc__.
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add.__doc__) # "Return the sum of a and b."
12. How do you take user input in Python?​
Use the built-in input() function. It reads a line from the user and returns it as a string. Convert to other types using int(), float(), etc.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
See User Input & Display.
13. What are keywords in Python?​
Keywords are reserved words in Python that have special meanings. They cannot be used as identifiers (variable names, function names). Examples: if, else, for, while, def, class, import, return, True, False, None, in, is, and, or, not. Use keyword.kwlist to see all keywords.
See Keywords & Literals.
14. What is indentation in Python?​
Indentation is Python's way of defining blocks of code (replacing curly braces in C/Java). A block is indented by 4 spaces or a tab (consistency required). Improper indentation causes IndentationError.
if True:
print("This is indented") # 4 spaces
15. What is pass?​
pass is a null statement that does nothing. It is used as a placeholder where syntax requires a statement but no action is needed.
def future_function():
pass # Will implement later
See Break/Continue/Pass.
🔵 Intermediate Questions​
1. Difference between deep copy and shallow copy?​
- Shallow copy: Creates a new object but inserts references to the original's nested objects. Changes to nested objects affect both. Use
copy.copy()orlist.copy(). - Deep copy: Creates a new object and recursively copies all nested objects. Changes are fully independent. Use
copy.deepcopy().
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 99 # Affects original
deep[0][0] = 99 # Does not affect original
2. What are decorators?​
Decorators are functions that modify the behavior of other functions or methods without changing their code. They use the @decorator syntax and are commonly used for logging, access control, timing, and memoization.
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"Time: {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
slow_function()
3. What are generators and the yield keyword?​
Generators are functions that use yield instead of return to produce a sequence of values lazily. Unlike regular functions, they remember their state between calls. They are memory-efficient for large datasets.
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
for num in count_up_to(5):
print(num) # 0, 1, 2, 3, 4
4. What are *args and **kwargs?​
*argsallows a function to accept any number of positional arguments as a tuple.**kwargsallows a function to accept any number of keyword arguments as a dictionary.
def example(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
example(1, 2, 3, name="Alice", age=25)
# Positional: (1, 2, 3)
# Keyword: {'name': 'Alice', 'age': 25}
5. What is list comprehension?​
A concise syntax for creating lists based on existing iterables. Format: [expression for item in iterable if condition].
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, ..., 81]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, ..., 18]
See List Comprehension.
6. What is lambda?​
A lambda is a small anonymous function defined in a single expression. Syntax: lambda arguments: expression.
add = lambda a, b: a + b
print(add(3, 5)) # 8
# Common use: sorting
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
pairs.sort(key=lambda x: x[0])
See Lambda Functions.
7. What is the with statement?​
The with statement simplifies resource management by ensuring that setup and cleanup actions are performed. It is commonly used for file operations and network connections. Objects used with with must implement the context manager protocol (__enter__ and __exit__).
# Without with
f = open("file.txt", "r")
content = f.read()
f.close()
# With with (auto-closes even on errors)
with open("file.txt", "r") as f:
content = f.read()
8. What are @classmethod and @staticmethod?​
@classmethod: A method that receives the class as the first argument (cls). Can modify class state. Used for alternative constructors.@staticmethod: A method that does not receiveselforcls. Behaves like a plain function but belongs to the class namespace.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@classmethod
def create_default(cls):
return cls()
print(MathUtils.add(3, 4)) # 7
9. What is __str__ vs __repr__?​
__str__: Called bystr()andprint(). Should return a readable, user-friendly string.__repr__: Called byrepr(). Should return an unambiguous string that ideally can recreate the object.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print(str(p)) # (3, 4)
print(repr(p)) # Point(3, 4)
10. How does exception handling work in Python?​
Python uses try/except/else/finally blocks to handle exceptions. Code that might raise an exception goes in try. Handlers go in except. The else block runs if no exception occurred. finally always runs for cleanup.
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid input. Must be a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
finally:
print("Execution complete.")
See Exceptions.
🟠Advanced Questions​
1. What is the GIL (Global Interpreter Lock)?​
The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously. This means CPython threads cannot achieve true parallelism for CPU-bound tasks. For I/O-bound tasks, threading is still useful. To bypass the GIL for CPU-bound work, use multiprocessing (separate processes) or use libraries like NumPy that release the GIL during computations.
2. What are metaclasses?​
A metaclass is a class of a class. Just as a class defines how objects behave, a metaclass defines how classes behave. The default metaclass is type. Metaclasses are used in frameworks like Django and SQLAlchemy for ORM model creation. They are considered an advanced feature and are rarely needed in everyday programming.
class Meta(type):
def __new__(cls, name, bases, dct):
dct['version'] = 1
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
print(MyClass.version) # 1
3. How do you create a custom context manager?​
Implement the __enter__ and __exit__ methods in a class, or use the @contextmanager decorator from contextlib.
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
f = open(filename, mode)
try:
yield f
finally:
f.close()
with open_file("test.txt", "w") as f:
f.write("Hello!")
4. Multiprocessing vs threading?​
| Feature | Threading | Multiprocessing |
|---|---|---|
| Memory | Shared | Separate |
| GIL | Affected | Bypassed |
| Best for | I/O-bound tasks | CPU-bound tasks |
| Overhead | Low | Higher |
| Starting | threading.Thread() | multiprocessing.Process() |
# Threading for I/O tasks
import threading
# Multiprocessing for CPU tasks
import multiprocessing
5. How does async/await work in Python?​
async/await enables concurrent code using an event loop. async def defines a coroutine. await suspends execution until the awaited coroutine completes. It is ideal for I/O-bound tasks like web requests and database queries.
import asyncio
async def fetch_data(url):
print(f"Fetching {url}...")
await asyncio.sleep(1) # Simulate network delay
return f"Data from {url}"
async def main():
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3")
)
print(results)
asyncio.run(main())
💻 Coding Challenges​
1. FizzBuzz (Beginner)​
Print numbers 1 to 100. For multiples of 3, print "Fizz" instead. For multiples of 5, print "Buzz". For multiples of both, print "FizzBuzz".
def fizzbuzz():
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz()
2. Palindrome Checker (Intermediate)​
Check whether a given string reads the same forward and backward (ignoring case, spaces, and punctuation).
def is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
# Test cases
print(is_palindrome("racecar")) # True
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(is_palindrome("hello")) # False
3. Fibonacci Generator (Intermediate)​
Generate the Fibonacci sequence up to n terms using a generator function.
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Print first 10 Fibonacci numbers
for num in fibonacci(10):
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
💡 Interview Tips​
| Tip | Explanation |
|---|---|
| Explain as you code | Talk through your thinking process — interviewers value reasoning over speed |
| Start with edge cases | Mention how you would handle empty inputs, invalid data, or large inputs |
| Write clean code | Use meaningful names, follow PEP 8, and keep functions small |
| Test your solution | Walk through an example input mentally after writing code |
| Say "I don't know" honestly | It is better than bluffing — then explain how you would find the answer |
| Ask clarifying questions | Confirm assumptions about input format, constraints, and expected output |
| Optimize after working solution | Get a working version first, then discuss time/space complexity improvements |
🔗 Related Resources​
- Python Practice Lab — More coding challenges
- Common Python Mistakes — Avoid pitfalls in interviews
- Python Projects — Build portfolio projects
- Glossary — Quick term lookup
- Data Structures Comparison — Understand when to use each
- OOP Concepts — Solidify OOP knowledge
Good luck with your interview! Remember: preparation beats nerves.