Top 100 Python Interview Questions and Answers
Q1: What is Python? basics
Python is a high-level, interpreted, dynamically-typed programming language known for its simple, readable syntax and versatility.
Q2: What is PEP 8? basics
PEP 8 is Python's style guide for writing clean, consistent, and readable code with conventions on naming, indentation, and formatting.
Q3: What are lists? collections
Lists are ordered, mutable collections of elements defined with square brackets []. They support indexing, slicing, and modification.
Q4: What are tuples? collections
Tuples are ordered, immutable collections defined with parentheses (). Once created, they cannot be modified.
Q5: What are dictionaries? collections
Dictionaries are unordered collections of key-value pairs used for fast lookups, defined with curly braces {}.
Q6: What are sets? collections
Sets are unordered collections of unique elements defined with set() or {}. They support union, intersection, and difference operations.
Q7: What is a function? functions
A function is a reusable block of code defined with def keyword. Functions can accept parameters and return values.
Q8: What is a lambda function? functions
Lambda is an anonymous function expression for small, one-time use functions. Syntax: lambda args: expression.
Q9: What is list comprehension? idioms
List comprehension is a concise syntax for building lists from iterables using expression and loop in one line.
Q10: What is a generator? advanced
A generator yields values lazily using yield keyword and implements the iterator protocol for memory efficiency.
Q11: What are decorators? advanced
Decorators wrap functions to add behavior before/after execution without changing the original function code.
Q12: What is exception handling? errors
Use try/except/finally blocks to catch runtime errors and handle them gracefully.
Q13: What is a context manager? advanced
Context managers implement __enter__/__exit__ methods and are used with with statement for safe resource management.
Q14: What are *args and **kwargs? functions
*args captures extra positional arguments as tuple; **kwargs captures extra keyword arguments as dictionary.
Q15: What is a module? organization
A module is a .py file containing functions, classes, and variables that can be imported for reuse.
Q16: What is a package? organization
A package is a directory containing an __init__.py file and submodules for organizing related code.
Q17: What is inheritance? oop
Inheritance lets a class derive properties and methods from a parent class using the extends mechanism.
Q18: What is polymorphism? oop
Polymorphism allows objects of different classes to be treated via a common interface.
Q19: What is encapsulation? oop
Encapsulation hides internal state and exposes only necessary methods through public interface.
Q20: What is method overriding? oop
Method overriding allows subclass to redefine parent class method with different implementation.
Q21: What is __init__? oop
__init__ is the constructor method called when an object is created to initialize its attributes.
Q22: What is __str__? oop
__str__ returns human-readable string representation of object used by print() and str().
Q23: What is __repr__? oop
__repr__ returns unambiguous debugging string representation of object for developer use.
Q24: What is __name__? basics
__name__ is set to '__main__' when script runs directly, allowing you to write code that runs only in that case.
Q25: What is threading? concurrency
Threading module enables lightweight threads for I/O-bound concurrency, limited by GIL for CPU-bound tasks.
Q26: What is multiprocessing? concurrency
Multiprocessing module enables true parallelism using separate processes to bypass GIL limitations.
Q27: What is GIL? advanced
Global Interpreter Lock prevents multiple threads from executing Python bytecode simultaneously in CPython.
Q28: What is pip? tools
pip is Python package installer used to download and install dependencies from PyPI.
Q29: What are virtual environments? tools
Virtual environments provide isolated Python installations with separate dependencies per project using venv.
Q30: What is requirements.txt? tools
requirements.txt lists project dependencies used by pip install -r to install all packages at once.
Q31: What is pyproject.toml? tools
pyproject.toml is the modern configuration file for Python packaging and build system settings.
Q32: What is __slots__? advanced
__slots__ restricts dynamic attributes on class instances and can significantly reduce memory overhead.
Q33: What is dataclass? oop
@dataclass decorator auto-generates __init__, __repr__, and other methods to reduce boilerplate code.
Q34: What is type hinting? advanced
Type hinting adds optional annotations for static type checking using tools like mypy.
Q35: What is isinstance? basics
isinstance() checks if an object is an instance of a class or tuple of classes.
Q36: What is issubclass? oop
issubclass() checks if a class is a subclass of another class.
Q37: What is zip()? builtins
zip() combines iterables into tuples and stops at the shortest input.
Q38: What is enumerate()? builtins
enumerate() returns index-element pairs for iterables in a loop.
Q39: What is map()? builtins
map() applies a function to each element of an iterable and returns an iterator.
Q40: What is filter()? builtins
filter() returns an iterator of items for which a predicate function returns True.
Q41: What is reduce()? functional
reduce() aggregates iterable elements using a binary function to accumulate a single result.
Q42: What is JSON? serialization
JSON module provides json.dumps/loads to serialize Python objects to JSON and vice versa.
Q43: What is pickle? serialization
pickle module serializes Python objects to byte streams and reconstructs them for storage.
Q44: What is pathlib? filesystem
pathlib provides object-oriented file path handling instead of string manipulation.
Q45: What is datetime? builtins
datetime module provides classes for working with dates, times, and timedeltas.
Q46: What is re (regex)? builtins
re module provides regular expression matching and substitution capabilities.
Q47: What is list slicing? basics
Slicing uses [start:stop:step] syntax to extract subsections from sequences.
Q48: What is unpacking? idioms
Unpacking uses * or ** to expand iterables and mappings in function calls and assignments.
Q49: What is copy module? advanced
copy module provides shallow and deep copy operations for flexible object duplication.
Q50: Value vs Reference? basics
Assignment binds names to objects; mutable objects can change when referenced by multiple names.
Q51: What is immutable? basics
Immutable objects cannot be modified after creation (str, tuple, frozenset, int).
Q52: What is contextlib? advanced
contextlib provides utilities to create and manage context managers and ExitStack.
Q53: What is namedtuple? collections
namedtuple factory creates tuple subclasses with named fields for better readability.
Q54: What is Enum? advanced
Enum module defines enumerated constant values with symbolic constants in classes.
Q55: What is abc? oop
abc module enables defining abstract base classes and abstract methods for enforcing interfaces.
Q56: What is subprocess? system
subprocess module spawns processes and interacts with OS commands.
Q57: What is requests? libraries
requests is a popular third-party library for making HTTP requests.
Q58: What is Flask? web
Flask is a lightweight web framework for building REST APIs and web applications.
Q59: What is Django? web
Django is a full-featured web framework for building production-ready applications.
Q60: What is FastAPI? web
FastAPI is optimized for high-performance async APIs using pydantic for data validation.
Q61: What is connection pooling? database
Connection pooling reuses database connections to reduce overhead and improve performance.
Q62: What is ORM? database
Object-Relational Mapping maps Python objects to database rows for easier database interaction.
Q63: What is SQLAlchemy? database
SQLAlchemy is a powerful Python ORM and SQL toolkit for database operations.
Q64: What is unit testing? testing
Unit testing tests small code units (functions/methods) with frameworks like unittest or pytest.
Q65: What is integration testing? testing
Integration testing verifies combined components and their interactions across modules.
Q66: What is pytest? testing
pytest is a popular testing framework with simpler syntax and powerful fixtures.
Q67: What is mock? testing
unittest.mock provides mocking capabilities to simulate objects for testing.
Q68: What is deadlock? concurrency
Deadlock occurs when threads wait indefinitely for resources locked by each other.
Q69: What is race condition? concurrency
Race condition happens with unsynchronized shared data access in concurrent code.
Q70: What is serialization? data
Serialization converts object data to storable format (JSON, pickle, msgpack).
Q71: What is deserialization? data
Deserialization rebuilds objects from persisted data format.
Q72: What is Cython? performance
Cython is a superset of Python to compile code to C for significant performance improvements.
Q73: What is asyncio? concurrency
asyncio library provides asynchronous I/O using async/await and event loops.
Q74: What is await? advanced
await pauses coroutine until the awaited awaitable completes.
Q75: What is async def? advanced
async def defines an asynchronous coroutine function that can use await.
Q76: What is pydantic? libraries
pydantic provides data validation and settings management using Python type annotations.
Q77: What is Black? tools
Black is a code formatter enforcing consistent style for Python projects automatically.
Q78: What is isort? tools
isort automatically sorts imports alphabetically and keeps imports organized.
Q79: What is mypy? tools
mypy is a static type checker that validates type hints in Python code.
Q80: What is Bandit? security
Bandit is a security linter for Python code detecting vulnerabilities.
Q81: What is openpyxl? libraries
openpyxl is a library to read and write Excel files programmatically.
Q82: What is garbage collection? advanced
Garbage collection automatically reclaims memory by removing unreferenced objects.
Q83: What is memory profiling? performance
Memory profiling tools track memory usage to identify leaks and optimize usage.
Q84: What is Protocol? advanced
Protocol from typing module enables structural typing for duck-type compatibility.
Q85: What is monkey patching? advanced
Monkey patching involves dynamically modifying modules or classes at runtime.
Q86: What is lazy loading? optimization
Lazy loading defers initialization until first use to save resources.
Q87: What is __enter__/__exit__? oop
Context manager methods for resource acquisition and cleanup with with statement.
Q88: What is __iter__/__next__? oop
Iterator protocol methods for making objects iterable in loops.
Q89: What is mutable default argument? gotchas
Default mutable arguments persist across calls; use None sentinel as workaround.
Q90: What is default_factory? advanced
default_factory in dataclass defines default values for mutable fields.
Q91: What is __all__? modules
__all__ defines public API symbols exportable with from module import *.
Q92: What is code coverage? testing
Code coverage percentage represents how much code is executed during tests (measured by coverage.py).
Q93: What is CI/CD? devops
Continuous Integration/Deployment automates testing and deployment on code changes.
Q94: What isinstance mutable types? types
Mutable types (list, dict, set) can be modified after creation.
Q95: What is production deployment? devops
Use Docker, CI/CD pipelines, and environment config to deploy stable Python services.
Q96: What is getattr/setattr? advanced
getattr/setattr dynamically access and set object attributes by name.
Q97: What is hasattr? basics
hasattr checks if object has a specific attribute by name.
Q98: What is vars? advanced
vars() returns __dict__ of object or module showing all attributes.
Q99: What is dir? basics
dir() lists names defined in module or attributes of object.
Q100: What is inspect? advanced
inspect module provides functions for getting source code, signatures, and debugging info.