Top 100 Python Interview Questions and Answers medium
Top 100 Python Interview Questions and Answers medium
14 1
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 1/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 2/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Because of its wide usage, Python is a common topic in job interviews for
software developers, data analysts, machine learning engineers, and other
tech roles. Whether you’re a fresher preparing for your first job, or a
professional looking to switch careers, understanding the most common
Python interview questions can help you feel more confident and perform
better.
In this guide, we have gathered the top 100 Python interview questions and
answers, starting from the basics and moving to more advanced topics. Each
answer is written in simple words and explained clearly with examples so
that anyone can understand — even if you’re just starting your Python
journey.
Let’s dive into the questions and get ready to ace your Python interview!
1. What is Python?
Python is a popular, high-level programming language that is easy to read
and write. It was created by Guido van Rossum and released in 1991. One of
the main reasons why Python is so widely used is because of its simple
syntax that looks like English. This makes it a great choice for beginners.
Python is also versatile — you can use it for web development, data science,
artificial intelligence, machine learning, automation, scripting, and more. It
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 3/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
is free to use and open-source, which means anyone can download and use
it. Big companies like Google, Instagram, and Netflix use Python in their
systems.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 4/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Variables in Python are used to store information that you want to use later.
Think of a variable as a box where you can keep something, like a number or
a name. You don’t need to mention the data type when creating a variable —
Python figures it out. For example:
name = "Alice"
age = 25
Here, name stores a string and age stores an integer. You can also change the
value of a variable anytime. Variables make it easy to write flexible programs
where data can change. You just use the variable name wherever you need
that value in your code.
is for whole numbers, float is for decimal numbers, and str is for text.
Python also has bool for True or False values, list for a collection of items,
tuple for an unchangeable group of items, dict for key-value pairs, and set
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 5/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
for unique items. These types help Python decide what kind of operations
can be done with the data. You don’t have to define the type—Python does it
automatically. Knowing data types is important to avoid errors and to use
functions correctly in your code.
You can add, remove, or change items in a list using functions like append() ,
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 6/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
You can access items in a tuple using an index like colors[0] . Tuples are
useful when you want to make sure that the data does not change. They are
also slightly faster than lists. Tuples can be used as keys in dictionaries, but
lists cannot because they are mutable. So, if you want to store fixed data,
tuples are a good choice.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 7/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
You can access the value by using the key: person["name"] returns "Alice" .
You can also add new key-value pairs or update existing ones. Dictionaries
are very useful when you need to store related information, like user details
or configuration settings. Keys must be unique and immutable, like strings
or numbers. Dictionaries are fast and great for looking up data by name or
key.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 8/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
numbers = {1, 2, 3, 2}
Sets are useful when you want to remove duplicates or check for common
values between groups using operations like union, intersection, and
difference. Since sets are unordered, you cannot access items using indexes.
Sets are also faster than lists when checking if an item exists. They are
simple but powerful for handling unique data.
'''
This is a
multi-line comment
'''
Good comments help others (and yourself) understand your code, especially
when it’s long or complex. They make your code more readable and easier to
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 10/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
define blocks of code. For example, in loops, conditionals, and functions, the
indented lines belong to the same code block. If indentation is not done
correctly, Python will raise an error and stop running. This makes Python
code more readable and clean. Here is a simple example:
if 5 > 2:
print("Five is greater than two")
In the above code, the print statement is indented, which shows that it
belongs to the if block. Proper indentation is very important in Python
programming.
def greet(name):
print("Hello, " + name)
You can call this function like greet("Alice") . Functions can take
parameters and can also return values using the return keyword. Using
functions makes your code shorter, cleaner, and easier to manage.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 13/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
name = "Alice"
print(name.upper()) # upper() is a method
In simple terms, all methods are functions, but not all functions are
methods. Methods always belong to an object or class, while functions do
not.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 14/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
In this case, name is a parameter, and "Alice" is the argument passed to the
function. Python also supports default arguments, keyword arguments, and
variable-length arguments. Understanding how parameters and arguments
work is important for writing flexible and reusable functions.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 15/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
return a + b
result = add(5, 3)
print(result) # Output: 8
In this case, the function add returns the sum of a and b, which is then
stored in the variable result . If there is no return statement, the function
will return None by default. Using return makes functions more useful
because they can provide output to be used later.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 16/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
The remove() method, on the other hand, is a list method that removes
the first occurrence of a specific value from the list. It raises a
ValueError if the item is not found:
nums = [1, 2, 3, 2]
nums.remove(2) # removes the first 2
In summary, use del when you know the index or want to delete a variable.
Use remove() when you want to delete a known value from a list.
18. What is the difference between for and while loops in Python?
The for loop and while loop are both used to repeat actions, but they are
used in different situations. A for loop is best when you know in advance
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 17/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
how many times you want to repeat something. It works well with lists,
strings, and ranges:
for i in range(5):
print(i)
A while loop is better when you don't know how many times you’ll repeat
and want to continue until a certain condition is false:
while i < 5:
print(i)
i += 1
So, use for when looping through known items, and use while when you
need to loop based on a condition.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 18/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
You can also use elif (short for "else if") to check multiple conditions:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 19/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
20. What is the use of the break , continue , and pass statements in Python?
for i in range(5):
if i == 3:
break
print(i) # Prints 0, 1, 2
continue : Skips the current loop cycle and moves to the next one:
for i in range(5):
if i == 3:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 20/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
continue
print(i) # Skips 3
pass : Does nothing. It’s used as a placeholder where code is needed later:
for i in range(5):
pass # To be implemented later
These are useful for controlling loops more precisely based on your
program’s needs.
21. What are Python lists and how do you use them?
A list in Python is a collection of items that can hold different types of values
like numbers, strings, or even other lists. Lists are ordered and changeable,
meaning you can update, add, or remove items. You define a list using
square brackets:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 21/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
You can access list items by index, like fruits[0] which gives "apple" . You
can also change values, like fruits[1] = "orange" . Python lists have many
useful functions like append() to add an item, remove() to delete an item,
and sort() to sort the list. Lists are one of the most used data types in
Python.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 22/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
You can change my_list[0] = 10 , but you cannot change my_tuple[0] . Tuples
are faster and take up less memory than lists. Use tuples when your data
should not change, such as coordinates or fixed settings. Lists are better
when you need to update, sort, or modify the data.
23. What are Python dictionaries and how are they used?
A dictionary in Python is a collection of key-value pairs. Each key is unique
and maps to a value. You create a dictionary using curly braces {} :
You can access values using keys, like person["name"] which gives "Alice" .
You can also add or update values, like person["age"] = 30 . Dictionaries are
useful when you want to store and retrieve data using names or identifiers
instead of positions. Some helpful functions include keys() , values() , and
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 23/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
items() . They are powerful for storing structured data, like JSON responses
or configuration settings.
24. What are Python sets and what are they used for?
A set is a collection of unique items. It is unordered, so the items do not have
a fixed position and cannot be accessed by index. Sets are defined using
curly braces {} :
my_set = {1, 2, 3}
If you try to add a duplicate, it will be ignored. Sets are useful for checking
membership and removing duplicates. You can use add() to insert elements
and remove() to delete them. Python also supports set operations like union
( | ), intersection ( & ), and difference ( - ). Sets are great when you need fast
lookups or want to ensure no duplicates exist.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 24/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, my name is " + self.name)
The __init__ method is the constructor and runs when a new object is
created. You can create an object like p1 = Person("Alice") and call its
method using p1.greet() . Classes help in object-oriented programming and
allow you to create reusable code.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 25/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
class Dog:
def __init__(self, name):
self.name = name
dog1 = Dog("Buddy")
Here, dog1 is an object of the Dog class. It has its own copy of data and can
use class methods. In Python, almost everything is an object—strings, lists,
functions, and even classes. Objects make code modular, reusable, and
organized.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.speak()
d.bark()
In this example, the Dog class inherits from Animal , so it can use the speak()
method. Inheritance supports code reuse and helps organize code better
when working with related classes.
class Dog:
def speak(self):
return "Bark"
class Cat:
def speak(self):
return "Meow"
Each object knows how to perform its version of the method. Polymorphism
makes code flexible and helps when writing functions that can work with
multiple types of objects.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 28/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
class Person:
def __init__(self, name):
self.__name = name # private variable
def get_name(self):
return self.__name
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 29/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Bark")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 30/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
These are useful for creating flexible functions, wrappers, and decorators.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 31/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
def main():
print("Running as a script")
if __name__ == "__main__":
main()
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 32/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
This is much cleaner than checking for key existence manually using get()
This creates a list [0, 1, 4, 9, 16] . You can also add conditions:
List comprehensions are useful when you want to transform or filter data
quickly. They make your code shorter, cleaner, and easier to understand than
using a full for loop.
Example:
def square(x):
return x * x
print(apply_twice(square, 2)) # Output: 16
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 35/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
class A:
def greet(self):
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 36/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
While powerful, multiple inheritance can make the class hierarchy hard to
manage, so it should be used with care. The super() function and MRO help
mitigate the complexity.
mypackage/
│
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 37/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
├── __init__.py
├── module1.py
└── module2.py
You can import modules from the package using dot notation:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 38/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
package. For example, you might import key modules or define variables
inside it:
# __init__.py
from .module1 import function1
With this, users can simply do from package import function1 instead of
importing the whole module. It helps organize imports and controls how
packages behave during import.
try:
num = int(input("Enter a number: "))
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 39/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
finally:
print("This always runs.")
The try block runs the risky code. If there’s an error, Python checks for a
matching except block. The finally block always runs, whether an error
occurred or not. Exception handling makes your programs more robust and
user-friendly.
41. What is the difference between break , continue , and pass in Python?
In Python, break , continue , and pass are control flow statements, but each
one serves a different purpose.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 40/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
for i in range(5):
if i == 3:
break
print(i)
continue : It skips the current iteration and moves to the next one without
stopping the loop.
for i in range(5):
if i == 3:
continue
print(i)
for i in range(5):
if i == 3:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 41/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
pass
print(i)
These are useful for controlling how loops and conditionals behave during
execution.
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def greet():
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 42/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
print("Hello!")
greet()
Here, @decorator wraps the greet() function and adds extra code before and
after it. Decorators are used often in logging, authentication, timing, and
access control. They help you write cleaner, reusable, and more readable
code.
Counter is a class from the collections module that helps count occurrences
of elements in an iterable. It returns a dictionary-like object where elements
are stored as keys and counts as values.
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 43/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
def outer(msg):
def inner():
print(msg)
return inner
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 44/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
greet = outer("Hello")
greet() # prints "Hello"
In the above code, the function inner() forms a closure—it remembers the
variable msg from its enclosing function outer() . Closures are useful for
building function factories, decorators, and keeping state in a clean and
elegant way.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 45/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
print(kwargs)
(1, 2, 3)
{'name': 'Alice', 'age': 25}
These features make your functions flexible and reusable. You can call them
with different numbers of parameters without changing the function
definition.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 46/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # prints "local"
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 47/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
The with statement automatically closes the file. You can also write to a file:
Use modes like "r" for reading, "w" for writing, and "a" for appending. File
operations are useful for data storage, configuration, and logging in
applications.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 48/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Each type serves different purposes. For example, use int for whole
numbers, str for text, list for ordered groups, and dict for key-value
pairs. Understanding data types helps you store and manipulate data
correctly in your programs.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 49/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
and set . You can add, remove, or change elements in these types.
float , str , and tuple . If you try to modify them, Python creates a new
object instead.
x = "hello"
x = x + " world" # Creates a new string
Knowing which types are mutable and which are not helps you avoid bugs,
especially when passing variables into functions. It also affects performance
and how memory is managed.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 50/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
Functions make your code reusable and organized. Instead of repeating the
same logic, you put it in a function and call it whenever needed. You can also
have default arguments, variable-length arguments, and even functions
inside functions.
By default, all classes in Python are instances of type , the default metaclass.
However, you can define custom metaclasses by inheriting from type , and
use them to automatically modify class attributes or behavior at the time of
class creation.
Example:
import math
math.sqrt = lambda x: "No square roots allowed"
print(math.sqrt(9)) # Outputs: No square roots allowed
Basic syntax:
Example:
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Lambdas are useful in places where a quick function is needed, like with
map() , filter() , and sorted() .
nums = [5, 2, 9]
sorted_nums = sorted(nums, key=lambda x: -x)
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 54/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
print(ClassName.__mro__)
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 55/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("No errors occurred.")
finally:
print("This will always run.")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 56/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Using exceptions helps in building robust applications that can recover from
unexpected situations.
Example:
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
book = Book("Python 101")
print(book) # Output: Book: Python 101
Magic methods make classes act like built-in types, improving readability
and flexibility.
In Python:
Example:
a = [1, 2, 3]
b = [1, 2, 3]
if my_var is None:
print("Value is None")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 59/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Use == for equality of content and is when you care about identity, such as
comparing singletons or cached objects.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
Lists are defined with square brackets [] , and tuples with parentheses () .
Lists are commonly used when data needs to change during runtime, while
tuples are ideal for fixed data or when you want to ensure the data stays
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 60/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I can quack too!")
def make_quack(thing):
thing.quack()
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 61/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
make_quack(Duck())
make_quack(Person())
Even though Duck and Person are different classes, both can be passed
because they have a quack() method. This flexibility makes Python code
more reusable and simple.
Each object has a reference count: when the count reaches zero, it is
deleted.
You don’t usually need to manage memory manually. Python handles it for
you. But you can still check or influence it using the gc module:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 62/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
import gc
gc.collect()
For example:
import gc
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 63/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
It’s particularly useful when dealing with circular references — where two
objects refer to each other, preventing their reference count from dropping
to zero. The gc module helps identify and clean these unreachable objects.
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 64/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
When there are no more items, next() raises a StopIteration error. Iterators
are memory-efficient because they don’t store the whole sequence in
memory, which is helpful for large datasets or file reading.
In Python, copy() and deepcopy() both come from the copy module and are
used to duplicate objects, but they behave differently:
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 65/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
import copy
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 66/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:4]) # [1, 2, 3]
print(my_list[::2]) # [0, 2, 4]
print(my_list[::-1]) # [5, 4, 3, 2, 1, 0]
text = "Python"
print(text[1:4]) # "yth"
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 67/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Both append() and extend() are used to add elements to a list, but they do it
differently:
append() adds a single element to the end of the list, even if it’s another
list.
extend() takes an iterable and adds each element from it to the list.
Example:
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]
So, append() adds the whole object, while extend() breaks it apart and adds
each item individually. Use append() when you want to keep an item
together; use extend() when you want to expand the list.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 68/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
The enumerate() function is used when you need both the index and value
while looping over an iterable. It adds a counter to the iterable and returns it
as an enumerate object, which you can convert into a list or use in a loop.
Example:
Output:
0 apple
1 banana
2 cherry
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 69/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
This is much cleaner than using range(len(fruits)) . You can also start the
index at a custom number by using enumerate(fruits, start=1) . It’s helpful
when you’re processing lists, keeping track of positions, or labeling items in
a report or UI.
filter() applies a function that returns True or False , and only keeps
items where the function returns True .
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 70/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
nums = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, nums))) # [2, 4, 6, 8]
print(list(filter(lambda x: x % 2 == 0, nums))) # [2, 4]
print(reduce(lambda x, y: x + y, nums)) # 10
map() transforms data, filter() selects data, and reduce() combines data.
They help write clean, short code for data processing.
The zip() function is used to combine two or more iterables into a single
iterable of tuples, where the i-th tuple contains the i-th element from each
iterable. It stops at the shortest input length.
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 71/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
If the input lists are of unequal length, the extra items are ignored. You can
also unzip using zip(*zipped_data) .
In Python:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 72/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
Output:
Args: (1, 2, 3)
Kwargs: {'a': 4, 'b': 5}
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 73/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
These are useful when writing flexible functions that can accept any number
of inputs. It helps when wrapping other functions or when you don’t know in
advance how many parameters might be passed.
Example:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 74/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Every recursive function must have a base case to prevent infinite recursion.
Python limits recursion depth by default (about 1000 calls). You can check it
using sys.getrecursionlimit() .
Recursion makes some problems easier to solve, though it may use more
memory than loops.
extension. Modules help organize and reuse code across multiple programs.
You can define functions, variables, and classes inside a module and then
import them into other files using the import statement.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 75/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
import math_utils
print(math_utils.add(2, 3))
Python has many built-in modules like math , random , and datetime . You can
also create your own custom modules to keep your code clean, organized,
and maintainable, especially in large projects.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 76/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r()) # Returns the object
del obj
print(r()) # Returns None (object is collected)
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 77/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
class Parent:
def __init__(self):
print("Parent initialized")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child initialized")
c = Child()
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 78/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
my_package/
__init__.py
module1.py
making them accessible directly from the package. It helps organize your
project structure for modular and maintainable code.
75. What is collections.deque and why is it better than a list for some use
cases?
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 79/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
While Python lists are efficient for append and pop operations at the end,
they are slow when inserting or deleting items at the beginning because all
elements must be shifted.
deque solves this by using a doubly linked list internally, allowing O(1)
operations on both ends:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 80/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
Use namedtuple when you need immutable data structures with readable
fields—ideal for data modeling, configuration, and return values.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 81/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 82/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 83/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Python annotations are a way to add type hints to function parameters and
return types. Introduced in PEP 484, they help improve code readability,
allow static type checkers like mypy to analyze your code, and assist with IDE
autocompletion.
Here, name is expected to be a string, and the function returns a string. You
can also access annotations using the __annotations__ attribute.
80. What are type hints and why are they useful in Python?
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 84/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Type hints (also called type annotations) allow developers to specify the
expected data types of function parameters and return values. Introduced in
Python 3.5 via PEP 484, they don’t change how code runs but help with
readability, autocompletion, and static type checking.
Example:
Tools like mypy can then analyze your code for type consistency without
running it. Type hints are valuable in large codebases and collaborative
projects.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 85/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
values are the objects those names refer to. Python uses namespaces to keep
track of all the names in your program, like variable names, function names,
class names, etc.
For example:
x = 10 # Global namespace
def func():
y = 5 # Local namespace
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 86/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Namespaces prevent naming conflicts and help Python know which variable
you’re referring to in different parts of the program. You can access
namespaces using functions like globals() and locals() .
Example:
x = 5 # Global
def my_func():
x = 10 # Local
print(x)
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 87/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
my_func() # Prints 10
print(x) # Prints 5
If you want to change the global variable inside a function, you must use the
global keyword:
def my_func():
global x
x = 20
Local variables help keep functions independent, while global variables can
be accessed across functions but may lead to unexpected behavior if not
managed properly.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 88/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
duplicate values, and they are not indexed, meaning you cannot access items
using indexes like my_set[0] .
Example:
my_list = [1, 2, 2, 3]
my_set = set(my_list) # {1, 2, 3}
Key differences:
Mutability: Both are mutable, but sets only contain immutable elements.
Use sets when you need to store unique values or perform set-based
operations efficiently.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 89/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This will always run.")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 90/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
try:
x = 5
except:
print("Error")
else:
print("No error")
Both repr() and str() are used to get string representations of objects, but
for different purposes:
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 91/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
s = "Hello"
print(str(s)) # Output: Hello
print(repr(s)) # Output: 'Hello'
You can override __str__() and __repr__() in custom classes for better
control over their behavior.86. What is None in Python?
Example:
x = None
if x is None:
print("x has no value")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 92/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Functions that don’t explicitly return anything will return None by default:
def greet():
print("Hello")
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 93/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
a = [1, 2, 3]
b = a
print(id(a), id(b)) # Same id
Even if two objects have the same value, they may not have the same id :
x = [1, 2]
y = [1, 2]
print(id(x) == id(y)) # False
You can combine id() with the is keyword to check identity. This is
especially useful when dealing with mutable and immutable types and
understanding object references.
Example:
Syntax:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 95/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
age = 18
status = "Adult" if age >= 18 else "Minor"
It makes code more concise and readable for small decisions. But avoid
using it for complex logic, as it can reduce readability. It’s commonly used
when assigning values based on a quick condition.
Example:
x = 5
assert x > 0, "x must be positive"
If x is less than or equal to 0, the assertion will fail. You can provide a
custom error message after the comma.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 97/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
You can use zip() for many tasks like combining data, iterating over
multiple sequences at once, or transposing rows and columns in matrices.
It's efficient and easy to use, often seen in data processing, file merging, or
where multiple iterables need to be processed in parallel.
The dir() function is a built-in utility that returns a list of all attributes and
methods (including inherited ones) available for a given object. It’s widely
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 98/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
For example:
When called with no arguments, dir() returns the list of names in the
current local scope.
The map() function applies a given function to all items in an iterable and
returns a map object (which is an iterator). It’s a clean way to apply
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 99/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Syntax:
map(function, iterable)
Example:
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # [1, 4, 9, 16]
map() is often used when you need to apply the same function to every
element. It's efficient and can be combined with other functional
programming tools like filter() or reduce() . It keeps code short and
readable.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 100/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Syntax:
filter(function, iterable)
Example:
numbers = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # [2, 4]
It is useful when you want to keep elements that meet certain criteria and
discard the rest. filter() makes your code more expressive and avoids
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 101/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
The reduce() function from the functools module applies a function to the
items of a sequence and reduces it to a single value. It processes the
sequence pairwise.
Syntax:
Example:
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 102/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Example:
fs = frozenset([1, 2, 3])
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 103/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
It supports all set operations like union, intersection, and difference. Use
frozenset when you need to ensure the contents of a set do not change,
especially when dealing with caching, memoization, or set-based keys.
Both yield and return are used in functions, but they work very differently.
return ends a function and sends back a value. Once return is called, the
function ends. On the other hand, yield pauses the function and sends a
value but keeps the function state alive for the next call.
With yield , the function becomes a generator. You can use next() to get the
next value from it.
Example:
def gen():
yield 1
yield 2
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 104/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
g = gen()
print(next(g)) # 1
print(next(g)) # 2
yield is memory-efficient and great for iterating over large or infinite data.
Example:
import gc
gc.collect() # Triggers garbage collection
Good practices like avoiding unnecessary global variables and closing files
and connections help manage memory better in Python.
Example:
Here, file is automatically closed when the block ends. This is better than
manually calling file.close() because it handles exceptions safely.
The with statement works with context managers, which define __enter__()
and __exit__() methods. It makes your code cleaner, safer, and easier to
maintain.
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 107/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
I’ve collected all this information from various reliable sources, articles, and
websites to bring you a comprehensive list of Python interview questions
and answers.
While I’ve tried my best to ensure everything is accurate and helpful, there’s
always a chance that something might need correction or improvement. If
you find anything incorrect or think something can be better explained,
please don’t hesitate to let us know in the comments section.
Your feedback will help make this resource more accurate and useful for
everyone preparing for their Python interviews. Let’s grow and learn
together! 💻🐍✨
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 108/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 109/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://drive.google.com/file/d/1hdC-E7Kf97NM3YzWKvpm5olb89kNrIcs/view
Interview Preparation
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 110/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Responses (1)
Khalilbattikh
Khalilbattikh You
May 20
Thank you for the list of questions and responses, but there are many repetitions.
5 1 reply Reply
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 111/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 112/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Flutter just got Flocked- Is Flutter Top 10 Flutter Database, that you
Dying should know about it
Understanding the Rise of Flock and Its here we discuss some major database
Impact on Flutter’s Stability and Future in… libraries that we must know
Jun 2 5 1 Jan 14 25 3
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 115/116
13/06/2025 01:39 Top 100 Python Interview Questions and Answers | by Shirsh Shukla | Medium
Help Status About Careers Press Blog Privacy Rules Terms Text to speech
https://shirsh94.medium.com/top-100-python-interview-questions-and-answers-4c4e9301d9b6 116/116