Python Interview Questions 2026
Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. Known for its simplicity, readability, and versatility, Python has become one of the most popular languages in the world.
Whether you're preparing for your first Python interview or aiming for senior roles at top tech companies, this comprehensive guide covers everything from fundamentals to advanced concepts including NumPy and Pandas.
Why is Python Popular?
Easy to Learn
Clean, human-readable syntax makes Python accessible to beginners
Interpreted Language
No compilation needed, enabling faster development cycles
Versatile
Used in web dev, data science, ML, automation, and more
Strong Community
Extensive libraries and frameworks with continuous updates
Python Use Cases
- Web Development — Django, Flask, FastAPI for dynamic websites and APIs
- Data Science & ML — NumPy, Pandas, Scikit-Learn, TensorFlow, PyTorch
- Automation & Scripting — Selenium, BeautifulSoup, Requests
- Cybersecurity — Penetration testing, vulnerability scanning
- Game Development — Pygame for 2D game creation
- IoT — Programming Raspberry Pi, Arduino
- GUI Development — Tkinter, PyQt, Kivy for desktop apps
Python Fundamentals
1. What is Python?
Python is a high-level, general-purpose, interpreted programming language created by Guido van Rossum in 1991. It emphasizes code readability with clean syntax and supports multiple programming paradigms — procedural, object-oriented, and functional. Python is widely used in web development, data science, AI/ML, automation, and scripting.
2. Is Python a compiled or an interpreted language?
Python is an interpreted language. The source code is executed line-by-line by the Python interpreter at runtime. However, Python first compiles .py files into bytecode (.pyc) internally, which is then executed by the Python Virtual Machine (PVM). This compilation is transparent to the user.
3. What is a dynamically typed language?
In a dynamically typed language, variable types are determined at runtime, not at compile time. You don't need to declare the type of a variable — it's inferred automatically.
x = 10 # x is int
x = "hello" # x is now str — no error
Python, JavaScript, and Ruby are dynamically typed. C, Java, and Go are statically typed.
4. What is PEP 8 and why is it important?
PEP 8 (Python Enhancement Proposal 8) is the official style guide for writing Python code. It defines conventions for:
- Indentation (4 spaces)
- Line length (79 characters)
- Naming conventions (snake_case for variables, PascalCase for classes)
- Spacing and documentation
Following PEP 8 makes code consistent, readable, and maintainable across teams.
5. Is indentation required in Python?
Yes — indentation is mandatory in Python. Unlike languages that use {} to define blocks, Python uses consistent indentation (typically 4 spaces) to group statements into blocks (functions, loops, conditionals, classes). Incorrect indentation raises an IndentationError.
Data Types and Structures
6. What is the difference between Mutable and Immutable data types?
| Feature | Mutable | Immutable |
|---|---|---|
| Can be changed | Yes | No |
| Examples | list, dict, set | int, float, str, tuple |
| Memory behavior | Modified in-place | New object created on change |
lst = [1, 2, 3]
lst[0] = 99 # valid — list is mutable
tup = (1, 2, 3)
tup[0] = 99 # TypeError — tuple is immutable
7. What are the built-in data types in Python?
- Numeric: int, float, complex
- Sequence: str, list, tuple, range
- Mapping: dict
- Set: set, frozenset
- Boolean: bool
- Binary: bytes, bytearray, memoryview
- None: NoneType
8. What are lists and tuples? What is the key difference?
List — mutable, ordered, defined with []. Can be changed after creation.
Tuple — immutable, ordered, defined with (). Cannot be changed after creation.
Use tuples for fixed data (coordinates, RGB values) and lists for data that changes. Tuples are slightly faster and can be used as dictionary keys.
9. What are negative indexes and why are they used?
Negative indexes allow accessing elements from the end of a sequence. -1 is the last element, -2 is second-to-last, etc.
lst = [10, 20, 30, 40]
print(lst[-1]) # 40
print(lst[-2]) # 30
10. What is slicing in Python?
Slicing extracts a portion of a sequence using [start:stop:step].
lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4]) # [1, 2, 3]
print(lst[::2]) # [0, 2, 4]
print(lst[::-1]) # [5, 4, 3, 2, 1, 0] (reverse)
Control Flow and Functions
11. What is the difference between / and // in Python?
/ — true division, always returns a float: 7 / 2 = 3.5
// — floor division, returns the integer part rounded down: 7 // 2 = 3
print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4 (rounds toward negative infinity)
12. What is a lambda function?
A lambda is an anonymous, single-expression function defined with the lambda keyword.
square = lambda x: x ** 2
print(square(5)) # 25
# Used inline with map/filter
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
13. What are *args and **kwargs?
*args — allows a function to accept any number of positional arguments as a tuple.
**kwargs — allows a function to accept any number of keyword arguments as a dictionary.
def demo(*args, **kwargs):
print(args) # (1, 2, 3)
print(kwargs) # {'name': 'Alice', 'age': 25}
demo(1, 2, 3, name="Alice", age=25)
14. What is self in Python?
self refers to the current instance of a class. It is the first parameter of every instance method and allows access to the object's attributes and other methods. It is passed automatically by Python when you call a method on an object.
Comprehensions and Generators
15. What is List Comprehension?
A concise way to create lists using a single line expression.
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x%2==0] # [0, 2, 4, 6, 8]
16. What are generators in Python?
Generators are functions that yield values one at a time using the yield keyword. They don't store all values in memory — values are produced lazily on demand. This makes them memory-efficient for large datasets.
def count_up(n):
for i in range(n):
yield i
for val in count_up(3):
print(val) # 0, 1, 2
17. What is the difference between yield and return?
| Feature | return | yield |
|---|---|---|
| Exits function | Yes, completely | Pauses and resumes |
| Returns | Single value | Value one at a time |
| State preserved | No | Yes |
| Creates | Regular function | Generator function |
Object-Oriented Programming
18. How do you create a class in Python?
class Dog:
species = "Canis lupus" # class attribute
def __init__(self, name):
self.name = name # instance attribute
def bark(self):
return f"{self.name} says Woof!"
d = Dog("Rex")
print(d.bark()) # Rex says Woof!
19. What is encapsulation in Python?
Encapsulation bundles data (attributes) and methods that operate on the data into a single unit (class), and restricts direct access from outside.
name— public, accessible from anywhere (default)_name— protected, single underscore, convention to indicate internal use__name— private, double underscore, name-mangled, not directly accessible
20. Does Python support multiple Inheritance?
Yes. Python supports multiple inheritance — a class can inherit from more than one parent class.
class A:
def greet(self): return "Hello from A"
class B:
def greet(self): return "Hello from B"
class C(A, B):
pass
c = C()
print(c.greet()) # "Hello from A" — MRO (Method Resolution Order)
Python uses the C3 linearization (MRO) to resolve method conflicts.
21. What are decorators in Python?
A decorator is a function that takes another function and extends or modifies its behavior without changing its source code. Uses the @ syntax.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def add(a, b):
return a + b
add(2, 3) # prints "Calling add", returns 5
Memory Management
22. How is memory managed in Python?
Python manages memory through:
- Private heap — all Python objects are stored in a private heap managed by the Python memory manager
- Reference counting — each object tracks how many references point to it; when count reaches 0, memory is freed
- Garbage collector — handles circular references that reference counting can't resolve (gc module)
- Memory pools — small objects (integers, strings) are cached and reused
23. What is the difference between shallow copy and deep copy?
Shallow copy — creates a new object but references the same nested objects. Changes to nested objects in the copy affect the original.
Deep copy — creates a completely independent copy including all nested objects.
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow[0][0]) # 99 — affected!
print(deep[0][0]) # 1 — not affected
Advanced Features
24. What is the Global Interpreter Lock (GIL)?
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems. This prevents race conditions in memory management but limits true CPU-bound parallelism with threads.
Solution: For CPU-bound tasks, use multiprocessing instead of threading. I/O-bound tasks benefit from threading despite the GIL.
25. What is the difference between @classmethod, @staticmethod, and instance methods?
| Type | First Param | Access to | Use case |
|---|---|---|---|
| Instance method | self | instance + class | Normal methods |
| @classmethod | cls | class only | Factory methods, alternative constructors |
| @staticmethod | none | neither | Utility functions logically related to the class |
26. What are Pickling and Unpickling?
Pickling — serializing a Python object into a byte stream (binary format) using the pickle module. Used to save objects to disk or send over a network.
Unpickling — deserializing the byte stream back into a Python object.
import pickle
data = {"name": "Alice", "age": 25}
# Pickle (serialize)
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
# Unpickle (deserialize)
with open("data.pkl", "rb") as f:
loaded = pickle.load(f)
NumPy
27. What is NumPy?
NumPy (Numerical Python) is a fundamental library for scientific computing in Python. It provides the ndarray (n-dimensional array) object and a large collection of mathematical functions to operate on arrays efficiently. It is the foundation for pandas, SciPy, TensorFlow, and most data science libraries.
28. How are NumPy arrays advantageous over Python lists?
| Feature | Python List | NumPy Array |
|---|---|---|
| Element types | Mixed | Homogeneous (same type) |
| Speed | Slower | Much faster (C-level operations) |
| Memory | More overhead | Compact, contiguous memory |
| Vectorized ops | Not supported | Built-in element-wise ops |
29. How to create NumPy arrays?
import numpy as np
arr1d = np.array([1, 2, 3]) # 1D
arr2d = np.array([[1, 2], [3, 4]]) # 2D
# Using creation functions
np.zeros((3, 3)) # 3x3 zeros
np.ones((2, 4)) # 2x4 ones
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # 5 evenly spaced values
Pandas
30. What is pandas?
Pandas is an open-source Python library for data manipulation and analysis. It provides two main data structures — Series (1D) and DataFrame (2D table) — and tools for reading, cleaning, transforming, and analyzing structured data. Built on top of NumPy.
31. What is a pandas DataFrame?
A DataFrame is a 2D labeled data structure with rows and columns, similar to a spreadsheet or SQL table. Each column is a Series. Columns can have different data types.
import pandas as pd
df = pd.DataFrame({
"name": ["Alice", "Bob"],
"age": [25, 30],
"score": [90.5, 85.0]
})
32. How to identify and deal with missing values?
df.isnull() # boolean mask of NaN locations
df.isnull().sum() # count of NaNs per column
df.dropna() # remove rows with any NaN
df.dropna(axis=1) # remove columns with any NaN
df.fillna(0) # replace NaN with 0
df.fillna(df.mean()) # replace with column mean
df.interpolate() # interpolate missing values
Master Python Through Practice! This guide covers essential Python interview questions from fundamentals to advanced topics. The key to success is hands-on coding, understanding the "why" behind each concept, and building real projects to solidify your knowledge.
Additional Resources
Best of luck with your Python interviews! Focus on understanding core concepts deeply, practice coding daily, work on real projects, and contribute to open source. Python's versatility means there's always something new to learn.