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