100 Python interview questions with their answers:
Python Basics
What is Python?
- Python is an interpreted, high-level, general-purpose programming language that emphasizes readability, simplicity, and flexibility.
What are Python's key features?
- Key features include dynamic typing, garbage collection, readability, support for both procedural and object-oriented programming, and extensive standard libraries.
What are Python's data types?
- Python supports several built-in data types: int, float, str, list, tuple, dict, set, bool, NoneType.
What is the difference between
list
andtuple
?- Lists are mutable (can be changed), whereas tuples are immutable (cannot be changed after creation).
What is a dictionary in Python?
- A dictionary is a collection of key-value pairs where keys are unique and values can be of any type.
What is a
set
in Python?- A set is an unordered collection of unique elements, supporting operations like union, intersection, and difference.
What is the difference between
del
andremove
in Python?del
deletes the object or item by index, whileremove
deletes an item by value.
What are Python functions?
- Functions in Python are defined using the
def
keyword, and they allow you to encapsulate logic for reuse.
- Functions in Python are defined using the
How can you declare a variable in Python?
- Variables are declared by assigning a value to a name:
x = 10
.
- Variables are declared by assigning a value to a name:
What is the
None
object in Python?None
is a special constant that represents the absence of a value or a null value.
Control Flow and Loops
What is the difference between
break
,continue
, andpass
?break
: Exits the current loop.continue
: Skips the current iteration and moves to the next one.pass
: A placeholder, does nothing.
What are
if
,elif
, andelse
in Python?if
: Executes a block of code if a condition is true.elif
: Executes a block of code if the previous condition(s) are false, and a new condition is true.else
: Executes a block of code if no preceding conditions are true.
How do you loop through a list in Python?
- Use a
for
loop:for item in my_list:
- Use a
What is the
range()
function?range()
generates a sequence of numbers, commonly used in loops:range(start, stop, step)
.
How does the
while
loop work?- A
while
loop repeatedly executes a block of code as long as a given condition is true.
- A
Functions and Lambda Expressions
What is a function in Python?
- A function is a block of reusable code that performs a specific task, defined using the
def
keyword.
- A function is a block of reusable code that performs a specific task, defined using the
What is a lambda function in Python?
- A lambda function is a small anonymous function defined with the
lambda
keyword. Example:lambda x: x + 2
.
- A lambda function is a small anonymous function defined with the
What is a return statement in Python?
- A
return
statement is used to exit a function and optionally return a value.
- A
What are default arguments in Python functions?
- Default arguments are parameters that have a predefined value. Example:
def func(a, b=5):
- Default arguments are parameters that have a predefined value. Example:
What is variable-length argument list in Python?
- You can pass a variable number of arguments to a function using
*args
(for non-keyword arguments) and**kwargs
(for keyword arguments).
- You can pass a variable number of arguments to a function using
Object-Oriented Programming (OOP)
What is OOP?
- Object-Oriented Programming is a paradigm based on objects and classes. It focuses on encapsulating data and functionality together.
What is a class in Python?
- A class is a blueprint for creating objects, defining properties and behaviors.
What is an object in Python?
- An object is an instance of a class containing both data (attributes) and methods (functions).
What are the four principles of OOP?
- Encapsulation, Abstraction, Inheritance, and Polymorphism.
What is inheritance in Python?
- Inheritance allows a class to inherit attributes and methods from another class, enabling code reuse.
What is polymorphism in Python?
- Polymorphism allows different classes to provide a method with the same name but different behaviors.
What is encapsulation in Python?
- Encapsulation is the bundling of data and methods that operate on the data within a class. It hides the internal state and allows access through methods.
What is abstraction in Python?
- Abstraction allows the hiding of complex implementation details while exposing only the necessary parts of the object.
What is the
self
keyword in Python?self
refers to the instance of the class, allowing access to instance attributes and methods.
What is the purpose of
__init__
in Python?__init__
is a special method used to initialize the object's attributes when an instance is created.
Modules and Packages
What is a module in Python?
- A module is a file containing Python definitions and statements that can be imported into other programs.
What is a package in Python?
- A package is a collection of Python modules organized in directories.
How do you import a module in Python?
- You can import a module using the
import
keyword:import module_name
.
- You can import a module using the
What is the difference between
import
andfrom
import?import
imports the whole module, whilefrom ... import
allows importing specific functions or variables.
What is the purpose of the
__name__
variable?- The
__name__
variable indicates the name of the module or script. It is__main__
when the script is executed directly.
- The
Exception Handling
What is exception handling in Python?
- Exception handling is a mechanism to handle runtime errors using
try
,except
,else
, andfinally
.
- Exception handling is a mechanism to handle runtime errors using
What is the purpose of
try
,except
,else
, andfinally
?try
: Block of code to attempt to execute.except
: Block of code to handle exceptions.else
: Block of code to run if no exceptions are raised.finally
: Block of code that runs regardless of whether an exception was raised.
What is the difference between
Exception
andError
?Exception
is a base class for all exceptions, whileError
refers to serious issues that are generally not caught by normal exception handling (e.g.,MemoryError
).
What is a custom exception?
- A custom exception is a user-defined class that extends the
Exception
class.
- A custom exception is a user-defined class that extends the
What is the
raise
keyword in Python?- The
raise
keyword is used to throw an exception explicitly in your code.
- The
Advanced Python Concepts
What is a generator in Python?
- A generator is a function that returns an iterator, yielding values one at a time using the
yield
keyword.
- A generator is a function that returns an iterator, yielding values one at a time using the
What are decorators in Python?
- Decorators are functions that modify the behavior of other functions or methods.
What is the difference between
deepcopy()
andcopy()
in Python?copy()
creates a shallow copy, whiledeepcopy()
creates a new object and recursively copies all nested objects.
What are metaclasses in Python?
- Metaclasses define how classes are created. They allow customization of class creation and behavior.
What is a context manager in Python?
- A context manager is used to manage resources, such as opening and closing files, using the
with
statement.
- A context manager is used to manage resources, such as opening and closing files, using the
What is the purpose of
global
keyword in Python?- The
global
keyword allows access to a global variable inside a function.
- The
What is the purpose of
nonlocal
keyword in Python?- The
nonlocal
keyword is used to modify variables in the nearest enclosing scope that is not global.
- The
What is a
staticmethod
in Python?- A
staticmethod
is a method that does not depend on instance variables or methods and can be called directly on the class.
- A
What is a
classmethod
in Python?- A
classmethod
is a method that takes the class as the first argument, and it is bound to the class rather than an instance.
- A
What is the
with
statement in Python?- The
with
statement simplifies resource management by ensuring that resources are properly acquired and released (e.g., for file handling).
- The
Libraries and Frameworks
What is
NumPy
?NumPy
is a Python library used for numerical computations, particularly for handling arrays and matrices.
What is
Pandas
?Pandas
is a Python library used for data manipulation and analysis, providing data structures like DataFrames.
What is
Matplotlib
?Matplotlib
is a plotting library for Python, used to create static, animated, and interactive visualizations.
What is
Flask
?Flask
is a micro web framework for Python that is used to build web applications.
What is
Django
?Django
is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
What is
requests
in Python?requests
is a popular library for making HTTP requests, handling things like headers, cookies, and response data.
What is
SQLAlchemy
?SQLAlchemy
is an Object Relational Mapping (ORM) library for Python, used to interact with databases using Python objects.
What is
TensorFlow
?TensorFlow
is an open-source machine learning framework developed by Google for building and training neural networks.
What is
Keras
?Keras
is a high-level neural networks API written in Python, running on top of frameworks like TensorFlow.
What is
scikit-learn
?scikit-learn
is a machine learning library for Python that provides simple and efficient tools for data analysis and modeling.
Python Best Practices
What are Python's PEP 8 guidelines?
- PEP 8 is the style guide for Python code, recommending practices like using 4 spaces for indentation, proper naming conventions, and line length restrictions.
What is the significance of
__str__
and__repr__
?__str__
is used for creating a user-friendly string representation of an object, while__repr__
is meant for a more formal representation that can be used to recreate the object.
What is list comprehension in Python?
- List comprehension provides a concise way to create lists based on existing lists or iterables. Example:
[x for x in range(10)]
.
- List comprehension provides a concise way to create lists based on existing lists or iterables. Example:
What is the purpose of
assert
in Python?- The
assert
statement is used for debugging purposes, ensuring that a condition holds true during program execution.
- The
What is the
zip()
function in Python?zip()
combines multiple iterables element-wise into tuples. Example:zip([1, 2], ['a', 'b'])
returns[(1, 'a'), (2, 'b')]
.
What is the difference between
del
andremove()
in a list?del
removes an item by index, whileremove()
removes an item by value.
How do you handle missing data in a pandas DataFrame?
- You can handle missing data using
dropna()
orfillna()
methods inpandas
.
- You can handle missing data using
What is the difference between
filter()
andmap()
in Python?filter()
filters items based on a condition, whilemap()
applies a function to each item in an iterable.
What is the difference between
join()
andsplit()
in Python?join()
concatenates a list of strings into one string, whilesplit()
breaks a string into a list based on a delimiter.
What is the use of
itertools
in Python?itertools
is a module providing functions for creating iterators that operate on items of an iterable, such as permutations and combinations.
Multithreading and Multiprocessing
What is the difference between
threading
andmultiprocessing
?threading
allows for concurrent execution of code using threads, whilemultiprocessing
runs code in separate processes.
What is the Global Interpreter Lock (GIL)?
- The GIL is a mechanism that ensures only one thread executes Python bytecode at a time, limiting the concurrency of multi-threaded programs.
How can you create a thread in Python?
- You can create a thread by using the
threading.Thread()
class and passing the target function to it.
- You can create a thread by using the
What is a lock in Python threading?
- A lock is a synchronization primitive used to ensure that only one thread accesses a shared resource at a time.
What is the
queue
module in Python?- The
queue
module provides a thread-safe FIFO implementation for passing data between threads or processes.
- The
File I/O and Serialization
How do you read a file in Python?
- Use the
open()
function andread()
method:with open('file.txt', 'r') as f: content = f.read()
.
- Use the
What is the difference between
open('file', 'r')
andopen('file', 'w')
?'r'
opens the file in read mode, while'w'
opens the file in write mode (creating a new file if it doesn't exist).
How do you write to a file in Python?
- Use the
write()
orwritelines()
method:with open('file.txt', 'w') as f: f.write('Hello World!')
.
- Use the
What is serialization in Python?
- Serialization is the process of converting an object into a byte stream, commonly using
pickle
orjson
modules.
- Serialization is the process of converting an object into a byte stream, commonly using
What is
pickle
in Python?pickle
is a Python module used for serializing and deserializing objects into byte streams.
Python Debugging and Testing
What is a debugger in Python?
- A debugger allows you to step through your code to inspect and troubleshoot it. Python provides the built-in
pdb
debugger.
- A debugger allows you to step through your code to inspect and troubleshoot it. Python provides the built-in
What is
unittest
in Python?unittest
is Python’s built-in framework for writing and running tests, supporting test discovery and execution.
What is the purpose of
assertEqual()
inunittest
?assertEqual()
checks whether two values are equal in unit tests.
What is
mock
in Python testing?mock
is a library used for creating mock objects to simulate and control parts of the code in tests.
What is the difference between
assertTrue
andassertFalse
inunittest
?assertTrue
checks if a condition isTrue
, whileassertFalse
checks if a condition isFalse
.
Performance Optimization
What are Python's performance bottlenecks?
- Performance bottlenecks can include inefficient use of data structures, redundant computations, excessive memory usage, and inefficient algorithms.
What is
cProfile
in Python?cProfile
is a built-in module used for profiling Python programs to identify performance issues.
What are some ways to improve performance in Python?
- Using built-in functions and libraries, optimizing algorithms, using
list comprehensions
, and usingNumPy
for numerical computations.
- Using built-in functions and libraries, optimizing algorithms, using
What is the difference between
range()
andxrange()
in Python 2?- In Python 2,
range()
returns a list, whilexrange()
returns an iterator. In Python 3,range()
behaves likexrange()
.
- In Python 2,
What is the use of
timeit
module in Python?- The
timeit
module is used for measuring execution time of small code snippets.
- The
Python Deployment
How can you create an executable from a Python script?
- You can create an executable using tools like
PyInstaller
orcx_Freeze
.
- You can create an executable using tools like
What is a virtual environment in Python?
- A virtual environment is an isolated environment where you can install and manage dependencies independently from the system installation.
How do you deploy a Python application?
- Deployment involves packaging the application, managing dependencies, setting up the environment, and running the application on the target platform.
What is
pip
in Python?pip
is Python’s package manager, used for installing and managing Python libraries.
What is Docker and how is it used with Python?
- Docker is a tool for creating containerized applications. It can be used to package and deploy Python applications consistently across environments.
Concurrency and Parallelism
What is the difference between concurrency and parallelism?
- Concurrency allows multiple tasks to run in an overlapping manner, while parallelism executes tasks simultaneously.
How do you create concurrent programs in Python?
- Use the
threading
,multiprocessing
, orasyncio
modules for creating concurrent programs.
- Use the
What is
asyncio
in Python?asyncio
is a module for writing asynchronous programs using coroutines, events, and non-blocking I/O.
What is the
async
keyword in Python?- The
async
keyword defines a coroutine function that can be used withawait
.
- The
How do you manage shared state between threads in Python? - You can use synchronization primitives such as
Lock
,Semaphore
, orQueue
from thethreading
module.
This concludes the 100 Python interview questions.