Here are 100 Python interview questions and answers, covering fundamentals, data structures, functions, object-oriented programming, advanced concepts, libraries, and real-world problem-solving.
Python Fundamentals
1. What is Python and why is it popular?
Python is a high-level, interpreted, general-purpose programming language known for its readability and simplicity. It’s popular because of its vast libraries, versatility (web, data science, automation), and strong community.
2. Is Python compiled or interpreted?
Python code is first compiled to bytecode (.pyc), which is then interpreted by the Python Virtual Machine (PVM). So it’s both compiled and interpreted, but generally called an interpreted language.
3. What is the difference between a list and a tuple?
Lists are mutable (can be modified after creation) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Tuples are faster and can be used as dictionary keys.
4. What are Python’s built-in data types?
Numeric: int, float, complex. Sequence: str, list, tuple, range. Mapping: dict. Set types: set, frozenset. Boolean: bool. Binary: bytes, bytearray, memoryview. None: NoneType.
5. How do you swap two variables in Python?a, b = b, a — this works because Python evaluates the right side first, creating a tuple, then unpacks it to the left side.
6. What does __name__ == "__main__" mean?
When a Python script is run directly, __name__ is set to "__main__". If imported as a module, __name__ is set to the module’s name. This check allows code to only execute when the file is run directly.
7. What is PEP 8?
Python Enhancement Proposal 8 — the style guide for Python code that covers indentation (4 spaces), line length (79 characters), naming conventions (snake_case for functions, CamelCase for classes), and whitespace rules.
8. What are Python’s keywords?
Reserved words that cannot be used as variable names: if, else, while, for, def, class, import, return, etc. Use import keyword; print(keyword.kwlist) to see all.
9. How does Python handle memory management?
Python uses automatic memory management with reference counting and cyclic garbage collector. Objects with zero references are immediately deallocated, and the garbage collector handles reference cycles.
10. What is the difference between deep copy and shallow copy?
Shallow copy (copy.copy()) creates a new object but inserts references to the original’s nested objects. Deep copy (copy.deepcopy()) recursively copies everything, creating a fully independent clone.
Data Types & Structures
11. What is a dictionary in Python?
An unordered (ordered from 3.7+), mutable collection of key-value pairs. Keys must be hashable and unique. Access is O(1) average time complexity.
12. What is a set in Python?
An unordered collection of unique, hashable elements. Supports mathematical set operations like union, intersection, and difference. Mutable (set) and immutable (frozenset) versions.
13. How do you remove duplicates from a list?
Convert to a set, then back to a list: list(set(my_list)). This does not preserve order. To preserve order, use: list(dict.fromkeys(my_list)).
14. What is list comprehension?
A concise way to create lists: [expression for item in iterable if condition]. Example: [x**2 for x in range(10) if x % 2 == 0].
15. What is the difference between append() and extend()?append() adds its argument as a single element to the end of a list. extend() iterates over the argument and adds each element individually.
16. What does *args and **kwargs mean?*args captures positional arguments as a tuple. **kwargs captures keyword arguments as a dictionary. Used to write flexible functions that accept any number of arguments.
17. What is slicing?
Extracting a subset of a sequence using [start:stop:step]. start is inclusive, stop is exclusive. Negative indices count from the end: my_list[-1] is the last element.
18. How are strings immutable in Python?
Once a string is created, it cannot be changed. Any operation that modifies a string actually creates a new string object.
19. What is None?
A special constant representing the absence of a value or a null value. It’s an instance of NoneType. Use is None to check, not ==.
20. What is the enumerate() function?
Adds a counter to an iterable and returns it as an enumerate object: for index, value in enumerate(list):.
Functions & Scope
21. What is a lambda function?
An anonymous inline function defined with lambda arguments: expression. Limited to a single expression. Often used with map(), filter(), sorted().
22. What are decorators?
Functions that wrap another function to extend or modify its behavior without permanently changing it. Uses @decorator_name syntax. Built on closures.
23. How does a decorator work internally?
It takes a function as input, defines an inner wrapper function that adds behavior before/after calling the original function, and returns the wrapper.
24. What is the difference between global and local variables?
Global variables are defined outside any function and are accessible throughout the module. Local variables are defined inside a function and exist only within that function’s scope.
25. What is the global keyword?
Declares a variable inside a function to refer to a global variable, allowing the function to modify it.
26. What is the nonlocal keyword?
Used in nested functions to refer to a variable in the nearest enclosing scope that is not global. Allows modification of variables in outer (but not global) scopes.
27. What is recursion?
A function calling itself to solve a problem by breaking it into smaller subproblems. Requires a base case to terminate. Example: factorial computation.
28. What is a generator?
A function that yields values one at a time using yield instead of return. It’s memory-efficient because it generates values on the fly without storing the entire sequence. Returns a generator object.
29. What is the difference between yield and return?return sends a value back and terminates the function. yield pauses the function, sends a value back, and can be resumed later to generate the next value.
30. What are map, filter, and reduce?map(func, iterable) applies a function to every item. filter(func, iterable) returns items where the function returns True. reduce(func, iterable) (from functools) cumulatively applies a function to reduce to a single value.
Object-Oriented Programming (OOP)
31. What is a class and an object?
A class is a blueprint or template for creating objects. An object is an instance of a class, containing attributes (data) and methods (behavior).
32. What is self in Python?
A reference to the current instance of the class. It’s the first parameter of instance methods and is used to access attributes and other methods belonging to that instance.
33. What is __init__?
The constructor method automatically called when an instance of a class is created. It initializes the object’s attributes.
34. What is inheritance?
A mechanism where a new class (child) derives properties and behavior from an existing class (parent). Promotes code reuse. Python supports multiple inheritance.
35. What is the difference between @staticmethod and @classmethod?@classmethod receives the class as the first argument (cls) and can modify class state. @staticmethod doesn’t receive any implicit first argument and behaves like a regular function within the class namespace.
36. What is encapsulation?
The bundling of data (attributes) and methods that operate on that data within a single unit (class). It restricts direct access to some components, using _protected and __private naming conventions.
37. What is polymorphism?
The ability of different classes to respond to the same method call in their own way. For example, both Dog and Cat classes might have a speak() method, but each returns a different sound.
38. What is method overriding?
A child class redefining a method inherited from the parent class, providing a specific implementation suitable to the child.
39. How does Python handle multiple inheritance?
Python uses the C3 linearization (MRO – Method Resolution Order) to determine the order in which base classes are searched for a method. Use ClassName.__mro__ to see the order.
40. What are dunder (magic) methods?
Special methods with double underscores before and after the name, like __str__, __repr__, __add__, __len__. They enable objects to interact with Python’s built-in operators and functions.
41. What is the difference between __str__ and __repr__?__str__ is for a readable, informal string representation (used by print()). __repr__ is for an unambiguous, official representation, ideally one that could recreate the object (used by repr() and debugging).
42. What are property decorators (@property)?
A way to define getters, setters, and deleters in a Pythonic way. @property makes a method accessible like an attribute, allowing controlled access to private attributes.
Modules, Packages & Files
43. What is a module in Python?
Any Python file (.py) containing functions, classes, or variables that can be imported into other Python files.
44. What is a package?
A directory containing an __init__.py file (can be empty) and other modules or sub-packages, allowing hierarchical organization of modules.
45. How do you import a module?import module_name, from module import function, from module import * (discouraged), or import module as alias.
46. What is __init__.py?
A file that makes Python treat a directory as a package. It can be empty or contain package initialization code and define the __all__ list for from package import *.
47. What is the Python Standard Library?
A large collection of modules and packages that come with Python, including modules for I/O, networking, data processing, and more (e.g., os, sys, json, datetime).
48. How do you read and write files in Python?
Use with open('filename', 'mode') as file: which ensures the file is properly closed. Modes: 'r' (read), 'w' (write), 'a' (append), 'rb' (binary read).
49. What is a context manager?
An object that defines __enter__ and __exit__ methods, used with the with statement to manage resources (like files, locks). Ensures setup and teardown are automatic.
50. What is pip?
The package installer for Python. Used to install and manage third-party libraries from PyPI (Python Package Index): pip install package_name.
Error Handling & Debugging
51. How do you handle exceptions in Python?
Using try, except, else, finally blocks. try runs the code, except catches specified exceptions, else runs if no exception, finally always runs (for cleanup).
52. What is the difference between a syntax error and an exception?
A syntax error occurs during parsing and prevents the program from running. An exception occurs during execution and can be handled to prevent the program from crashing.
53. What is raise used for?
To manually trigger an exception. You can raise built-in or custom exceptions.
54. What is the finally block for?
It executes code whether an exception occurred or not. Used for cleanup actions like closing files or releasing resources.
55. How do you create a custom exception?
By creating a new class that inherits from Exception (or a more specific exception type).
Functional & Advanced Concepts
56. What are iterators?
An object that implements __iter__() and __next__() methods, allowing iteration over a sequence. Lists, tuples, dictionaries, and generators are iterable.
57. What is the difference between an iterable and an iterator?
An iterable is an object that can return an iterator (__iter__ returns an iterator). An iterator is an object that maintains state and produces the next value (__next__). Every iterator is iterable, but not every iterable is an iterator.
58. What is a closure?
A function that remembers and has access to variables from its enclosing (outer) lexical scope even after the outer function has finished executing. Created when a nested function references a value from its enclosing function.
59. What are coroutines in Python?
Functions that can be paused and resumed, defined with async def and using await. They are the basis for asynchronous programming with asyncio.
60. What is asyncio?
A library that provides infrastructure for writing single-threaded concurrent code using async/await syntax, ideal for I/O-bound tasks.
61. What is the Global Interpreter Lock (GIL)?
A mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode simultaneously. It limits true multi-threading for CPU-bound tasks in CPython.
62. What is the difference between multithreading and multiprocessing?
Threads share the same memory space and are limited by the GIL (good for I/O-bound tasks). Processes have separate memory, bypass the GIL (good for CPU-bound tasks). Use threading and multiprocessing modules.
63. What is monkey patching?
Dynamically modifying a module, class, or function at runtime. Can be useful for testing or hotfixes but can make code harder to maintain.
64. What is __slots__?
A class attribute that restricts the instance attributes to a fixed set, preventing the creation of __dict__. Saves memory but reduces flexibility.
65. What are metaclasses?
Classes of classes — they define how a class behaves. A class is an instance of a metaclass. type is the default metaclass. Used for advanced frameworks (Django ORM, SQLAlchemy).
Common Libraries & Frameworks
66. What is NumPy?
A library for numerical computing in Python, providing support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on them.
67. What is pandas?
A data manipulation and analysis library built on NumPy, providing DataFrames and Series for handling structured data.
68. What is Django?
A high-level Python web framework that follows the MVT (Model-View-Template) pattern. It includes an ORM, authentication, admin panel, and many built-in features for rapid development.
69. What is Flask?
A micro web framework for Python. Lightweight and flexible, providing the essentials (routing, template rendering) and leaving additional features (ORM, auth) to extensions.
70. What is SQLAlchemy?
A SQL toolkit and ORM that allows Python developers to interact with databases using Python objects instead of raw SQL.
71. What is pytest?
A testing framework that simplifies writing small, readable tests and can scale to support complex functional testing.
72. What is Celery?
A distributed task queue for handling asynchronous tasks and scheduling in Python, often used for background jobs like sending emails.
73. What is Redis?
An in-memory data structure store used as a database, cache, and message broker. Often used with Python for caching and task queuing.
74. What is BeautifulSoup?
A library for parsing HTML and XML documents. Used for web scraping, it creates a parse tree for easy data extraction.
75. What is Jupyter Notebook?
An interactive web-based environment that allows users to create and share documents containing live code, equations, visualizations, and narrative text.
Testing & Best Practices
76. What is unit testing?
Testing individual units/components (functions, methods) in isolation to ensure they work correctly. Python’s standard library includes unittest.
77. What is the difference between unittest and pytest?unittest is in the standard library, requires more boilerplate (class-based). pytest uses simple function-based tests, powerful fixtures, and has a rich plugin ecosystem.
78. What are docstrings?
Strings that document a module, class, function, or method, placed as the first statement. Accessed via __doc__ attribute or help() function.
79. What is logging in Python?
The logging module provides a flexible framework for emitting log messages from applications. Levels include DEBUG, INFO, WARNING, ERROR, CRITICAL.
80. What is a virtual environment?
An isolated Python environment that allows you to install packages per project without affecting the global Python installation. Created with venv or virtualenv.
Problem-Solving & Coding Patterns
81. How do you reverse a string in Python?my_string[::-1]
82. How do you check if a string is a palindrome?s == s[::-1]
83. How do you find the most frequent element in a list?max(set(lst), key=lst.count)
84. Write a function to check if a number is prime.
python
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0: return False
return True
85. How do you merge two dictionaries?{**dict1, **dict2} or dict1 | dict2 (Python 3.9+).
86. How do you flatten a list of lists?
List comprehension: [item for sublist in my_list for item in sublist].
87. What does zip() do?
Combines iterables element-wise into tuples: zip([1,2], ['a','b']) produces (1,'a'), (2,'b').
88. How do you handle missing keys in a dictionary?
Using dict.get(key, default) which returns the default value if the key doesn’t exist.
89. What is defaultdict?
A dictionary from the collections module that returns a default value (instead of raising KeyError) when a missing key is accessed.
90. What is Counter used for?
A dict subclass in collections for counting hashable objects. It returns counts of elements in an iterable.
Advanced & Niche Topics
91. What is the difference between shallow and deep copy?
(Already asked, but emphasize:) Shallow copy duplicates the container but references internal objects. Deep copy duplicates everything recursively.
92. How do you profile Python code?
Using cProfile module for function-level profiling, timeit for small snippets, and line_profiler for line-by-line analysis.
93. What are * and ** operators besides multiplication/exponentiation?* unpacks iterables (lists, tuples). ** unpacks dictionaries. Used in function calls and assignment targets: first, *rest = my_list.
94. What is __new__?
A static method called before __init__ that creates and returns a new instance. It’s responsible for object creation, while __init__ handles initialization.
95. What are dataclasses?
A decorator (@dataclass) and base class that automatically generates boilerplate code like __init__, __repr__, __eq__ for classes that primarily store data.
96. How does Python’s garbage collection work?
Primarily reference counting with a cycle-detecting garbage collector (generational) that handles reference cycles. The gc module provides access to the collector.
97. What is the atexit module?
Allows you to register functions that will be called when a program terminates normally. Used for cleanup tasks.
98. Explain the difference between is and ==.is checks identity (same object in memory). == checks equality (same value). Use is for singletons like None.
99. What are namedtuple?
A factory function from collections that creates tuple subclasses with named fields, combining the immutability of tuples with attribute-style access.
100. How do you keep learning Python and stay updated?
By reading Python Enhancement Proposals (PEPs), following the Python Software Foundation blog, contributing to open source, building projects with new libraries, and participating in the Python community (forums, conferences, and reading “Fluent Python”).