Fullstack Training Center

Python Interview Questions

Python Interview Questions For Freshers

1. What is Python?
Python is a high-level, interpreted programming language that is versatile and uses dynamic semantics. It allows for object-oriented, procedural, and functional programming styles.

2. What are Python’s key features?

  • Easy to learn and use.
  • Interpreted language.
  • Cross-platform compatibility.
  • Dynamically typed.
  • Large standard library and active community support.

3. What is PEP 8?

PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices on how to write Python code for maximum readability.

4. How is memory managed in Python?
Python uses automatic memory management, including garbage collection. The memory manager handles object allocation and deallocation.

5. What distinguishes a list from a tuple?
Lists are mutable, meaning they can be changed after creation, while tuples are immutable and cannot be changed once defined.

6. How to handle exceptions in Python?
You can handle exceptions using try, except, else, and finally blocks.
try:
# code that may raise an exception
except SomeException:
# handle the exception
else:
# executed if no exception occurs
finally:
# executed always.

7. What are Python decorators?
Decorators allow you to change or improve functions or methods without altering their original code. They are typically marked with the @decorator_name format.

8. What are Python namespaces?
A namespace is a collection of names that reference objects. It ensures that names in a program do not conflict.

9. What are Python modules and packages?
A module is one Python file that has definitions and statements. A package is a group of modules arranged in folders.

10. Explain list comprehension.
List comprehension offers a simple method to generate lists.
# Example
squares = [x**2 for x in range(10)]

11. What is self in Python?
The self keyword refers to the specific instance of a class, enabling access to the class’s attributes and methods.

12. What is the difference between is and ==?
is checks for object identity (whether two references point to the same object), whereas == checks for value equality.

13. What is a lambda function?
Lambda functions are functions without a name, created using the lambda keyword. They can take multiple arguments but can only contain one expression.
add = lambda x, y: x + y

14. **What are *args and kwargs?
*args lets you send a flexible number of positional arguments..
kwargs allows you to pass a variable number of keyword arguments.

15. What is slicing in Python?
Slicing is a way to extract a portion of a list, tuple, or string by specifying a start, stop, and step.
lst = [1, 2, 3, 4, 5]
print(lst[1:4]) # Output: [2, 3, 4]

16. What is a Python generator?
A generator is a function that returns an iterator and generates values one at a time using yield.

17. What is the with statement in Python?
The with statement simplifies exception handling by encapsulating common cleanup tasks. It makes sure that resources are managed well.
with open(‘file.txt’, ‘r’) as file:
content = file.read()

18. What is the Global Interpreter Lock (GIL)?
The GIL is a lock that keeps Python objects safe by stopping more than one thread from running Python code at the same time. This ensures that Python threads are safe, but it restricts multi-threading in programs that need a lot of CPU power.

19. What is the difference between deep copy and shallow copy?
A shallow copy copies references to objects, whereas a deep copy copies the objects themselves.

20. What is monkey patching?
Monkey patching means changing or adding to a module or class while the program is running.

21. What are Python iterators?
Iterators are objects that implement the __iter__() and __next__() methods to return data one element at a time.

22. How do you create an iterator?
By defining a class with the __iter__() and __next__() methods.
class Counter:
def __iter__(self):
self.current = 0
return self
def __next__(self):
self.current += 1
return self.current

23. What are Python metaclasses?
Metaclasses are special classes that control how other classes function. A class is made using a metaclass.

24. What is list mutability in Python?
Lists in Python are mutable, meaning you can change their content by adding, modifying, or deleting elements.

25. What is the difference between remove(), pop(), and del?
remove() deletes the first instance of an element.
pop() removes and returns an element at a specific index.
del removes an element at a specific index but doesn’t return it.

26. What is the difference between sort() and sorted()?
sort() modifies the list in place, while sorted() returns a new sorted list without modifying the original list.

27. What is the __init__ method in Python?
The __init__ method acts as a constructor in Python classes.. It is automatically called when a new instance of a class is created.

28. How can you swap two variables in Python?
a, b = b, a

29. What is the pass statement in Python?
The pass statement is a no-operation statement used as a placeholder where code will go in the future.

30. What is the difference between append() and extend()?
append() adds its argument as a single element to the end of a list, while extend() appends the elements of an iterable to the list.

31. How do you concatenate strings in Python?
By using the + operator or join() method.
s1 = “Hello”
s2 = “World”
result = s1 + ” ” + s2

32. What is the difference between range() and xrange()?
In Python 2, range() returns a list, whereas xrange() returns an iterator. In Python 3, xrange() is removed and range() behaves like xrange().

33. What is the use of the dir() function?
The dir() function returns a list of valid attributes of an object.

34. What is a class method in Python?
A class method is a method linked to the class itself rather than to an instance. It is created with the @classmethod decorator.

35. What are Python’s built-in data types?
Common built-in data types are:
Numbers (int, float, complex)
Strings (str)
Lists
Tuples
Dictionaries (dict)
Sets
Booleans (bool)

36. What is the difference between isinstance() and type() in Python?
isinstance() checks if an object is an instance or subclass of a class or type, while type() returns the exact type of an object.
isinstance(5, int) # True
type(5) == int # True

37. What are Python magic methods?
Magic methods (also known as dunder methods) are special methods surrounded by double underscores that allow object-oriented features like operator overloading, e.g., __init__, __str__, __add__.

38. How do you convert a string to a list in Python?
You can use the list() constructor or split() method.
s = “Hello World”
lst = list(s) # Converts to [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
lst = s.split() # Converts to [‘Hello’, ‘World’]

39. What are Python closures?
A closure is a function object that remembers values in the enclosing lexical scope, even when the program flow is no longer in that scope.
def outer(x):
def inner(y):
return x + y
return inner
add_5 = outer(5)
print(add_5(10)) # Output: 15

40. What is the difference between a Python iterator and iterable?
An iterable is any Python object capable of returning its elements one at a time (e.g., lists, tuples). An iterator is an object that produces values from an iterable with the __next__() method.

41. Explain how the map() function works.

map() takes a specific function and applies it to every item in a list (or any iterable), then gives back an iterator.def square(x):
return x ** 2
result = map(square, [1, 2, 3, 4]) # Output: [1, 4, 9, 16]

42. How does the filter() function work?
filter() filters elements from an iterable that return True for a given function.
def is_even(x):
return x % 2 == 0
result = filter(is_even, [1, 2, 3, 4]) # Output: [2, 4]

43. What is the reduce() function?
reduce() applies a function cumulatively to items in an iterable, reducing them to a single value. It’s available in the functools module.
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4]) # Output: 10

44. What is a Python set?
A set is a collection of distinct items that do not have a specific order. Sets are mutable and support operations like union, intersection, and difference.

45. What is the difference between discard() and remove() in a set?
remove() raises a KeyError if the element does not exist, while discard() does nothing if the element is not found.

46. How to merge two dictionaries in Python?
You can merge two dictionaries using the update() method or the | operator (Python 3.9+).
dict1 = {‘a’: 1, ‘b’: 2}
dict2 = {‘b’: 3, ‘c’: 4}
dict1.update(dict2) # {‘a’: 1, ‘b’: 3, ‘c’: 4}

47. What is the difference between a staticmethod and a classmethod?
A classmethod takes cls as the first parameter and is bound to the class, while a staticmethod does not take self or cls and is independent of the class or instance.

48. What is the purpose of the assert statement?
assert is used for debugging purposes. It tests if a condition is true; if not, it raises an AssertionError.
assert 2 + 2 == 4 # No error
assert 2 + 2 == 5 # Raises AssertionError

49. Explain the use of the zip() function.
zip() combines multiple iterables into tuples.
a = [1, 2, 3]
b = [‘a’, ‘b’, ‘c’]
result = zip(a, b) # Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’)]

50. How to create a thread in Python?
You can use the threading module to create threads.
import threading
def print_numbers():
for i in range(5):
print(i)

thread = threading.Thread(target=print_numbers)
thread.start()

Python Interview Questions For Experienced

51. What are Python data classes?
Data classes, introduced in Python 3.7, are a way to create classes that mainly contain data attributes, reducing boilerplate code.
from dataclasses import dataclass

@dataclass
class Point:
x: int
y: int

52. What are frozen sets?
Frozen sets represent immutable forms of sets. Once established, the elements within them cannot be altered.
s = frozenset([1, 2, 3])

53. How to reverse a list in Python?
You can use slicing [::-1], the reverse() method, or the reversed() function.
lst = [1, 2, 3, 4]
lst.reverse() # In-place reversal
lst = list(reversed(lst)) # Returns reversed list

54. How to check for memory usage of an object in Python?
You can use the sys.getsizeof() function to check the memory size of an object.
import sys
sys.getsizeof(42) # Output: 28

55. Explain list slicing in Python.
List slicing allows you to access parts of a list. The syntax is [start:stop:step]
lst = [1, 2, 3, 4, 5]
print(lst[1:4]) # Output: [2, 3, 4]
print(lst[::-1]) # Output: [5, 4, 3, 2, 1]

56. What is a Python module?
A module refers to a Python file that encompasses functions, classes, and variables. It can be imported by utilizing the import statement.
57. What is a Python package?
A package is a collection of modules. It is typically organized into directories and includes an __init__.py file.

58. How to handle missing keys in a dictionary?
You can use dict.get() to return a default value if a key is missing.
my_dict = {‘a’: 1}
print(my_dict.get(‘b’, ‘Key not found’)) # Output: ‘Key not found’

59. Explain how to use the try-except-else-finally block in Python.
The try block allows for the examination of a segment of code for potential errors. The except block is responsible for managing exceptions. The else block runs when no exceptions are encountered, while the finally block is guaranteed to execute at the conclusion of the process.
try:
x = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero”)
else:
print(“No errors occurred”)
finally:
print(“This block is always executed”)

60. What is __name__ == ‘__main__’ in Python?
When a Python script is executed, the __name__ variable is assigned the value “__main__”.This conditional allows code to run only when the script is executed directly, not when it’s imported as a module.
if __name__ == “__main__”:
print(“Script is running directly”)

61. Explain the use of the global keyword in Python.
The global keyword allows you to modify a variable that is defined in the global scope from within a function.
x = 10

def modify_global():
global x
x = 20

62. What is the nonlocal keyword in Python?
nonlocal allows you to modify variables from the enclosing (non-global) scope.
def outer():
x = 10
def inner():
nonlocal x
x = 20

63. How to flatten a list of lists in Python?
You may utilize either list comprehension or the itertools.chain() function.
lst = [[1, 2], [3, 4], [5]]
flattened = [item for sublist in lst for item in sublist]

64. Explain the use of the any() and all() functions.
The function any() yields True if at least one element within an iterable evaluates to true. Conversely, the function all() produces True only if every element in the iterable is true.
any([0, 1, 0]) # True
all([1, 2, 3]) # True

65. What are Python list comprehensions?
List comprehensions provide a concise way to create lists by applying expressions to each item in an iterable.
squares = [x * x for x in range(10)]

66. What are Python dictionary comprehensions?
Dictionary comprehensions are a concise way to create dictionaries using an expression and an iterable.
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

67. How do you remove duplicates from a list in Python?
To eliminate duplicates, one can transform the list into a set and subsequently convert it back into a list.
lst = [1, 2, 2, 3, 4, 4]
lst = list(set(lst)) # Output: [1, 2, 3, 4]

68. What is the difference between deep copy and shallow copy in Python?
A shallow copy creates a new object but references the original elements (only one level deep), whereas a deep copy creates a completely new object and recursively copies all nested objects.
import copy
shallow = copy.copy(obj)
deep = copy.deepcopy(obj)

69. Explain the use of the id() function in Python.
The id() function returns the identity (unique memory address) of an object.
x = 10
print(id(x)) # Output: Some unique integer

70. How do you generate random numbers in Python?
The random module can be utilized to produce random numbers.
import random
random_number = random.randint(1, 10) # Generates a random number between 1 and 10

71. What is the difference between split() and partition() in Python?
split() divides a string into a list based on a delimiter, while partition() splits the string into a tuple of three parts: the part before the separator, the separator itself, and the part after the separator.
s = “Hello World”
print(s.split()) # [‘Hello’, ‘World’]
print(s.partition(” “)) # (‘Hello’, ‘ ‘, ‘World’)

72. How do you sort a list of dictionaries by a value in Python?
The sorted() function can be utilized by incorporating a key argument.
lst = [{‘name’: ‘John’, ‘age’: 25}, {‘name’: ‘Jane’, ‘age’: 22}]
sorted_lst = sorted(lst, key=lambda x: x[‘age’]) # Sort by age

73. What are function annotations in Python?
Function annotations are a way to attach metadata to function arguments and return values using a colon (:) for arguments and an arrow (->) for return values.
def add(x: int, y: int) -> int:
return x + y

74. What is the with statement used for in Python?
The with statement simplifies exception handling by ensuring that resources are properly acquired and released. It’s often used for file operations.
with open(‘file.txt’, ‘r’) as f:
content = f.read()

75. What is __slots__ in Python?
__slots__ is used to restrict the creation of instance attributes to only those listed, reducing memory usage by preventing the creation of __dict__ for instances.
class MyClass:
__slots__ = [‘name’, ‘age’]

76. Explain the use of super() in Python.
super() is used to call methods from a parent class, making inheritance more manageable and avoiding calling parent classes explicitly.
class Parent:
def greet(self):
print(“Hello from Parent”)

class Child(Parent):
def greet(self):
super().greet()
print(“Hello from Child”)

77. What is the purpose of the enumerate() function in Python?
enumerate() adds a counter to an iterable and returns it in the form of an enumerating object (index, item pairs).
lst = [‘a’, ‘b’, ‘c’]
for index, value in enumerate(lst):
print(index, value) # Output: (0, ‘a’), (1, ‘b’), (2, ‘c’)

78. What is the difference between range() and xrange()?
xrange() was used in Python 2 and returned an iterator, while range() in Python 3 returns a range object, which is more memory efficient than lists.

79. How do you check if a string contains a substring in Python?
One can utilize the in keyword to determine whether a substring is present within a string.
s = “Hello World”
if “World” in s:
print(“Substring found”)

80. What are the Python built-in types for binary data handling?
The primary types for binary data are bytes, bytearray, and memoryview.

81. How can you get the current working directory in Python?
You can use the os.getcwd() function to get the current working directory.
import os
cwd = os.getcwd() # Returns the current working directory

82. What is the yield keyword used for in Python?
yield is used to return a generator, which can be iterated over. It pauses the function and saves its state for resuming later.
def count_up_to(max):
n = 1
while n <= max:
yield n
n += 1

83. How do you create a lambda function in Python?
A lambda function is a concise, unnamed function that can accept multiple arguments while containing a single expression.
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

84. What is the difference between break, continue, and pass in Python?
break: Exits the current loop prematurely.
continue: Bypasses the present iteration and proceeds to the subsequent one. pass: Performs no action and functions as a placeholder.

85. What is monkey patching in Python?
Monkey patching is the dynamic modification of a class or module at runtime. This technique is often used in testing or to modify third-party code.
class MyClass:
def original_method(self):
print(“Original”)

def new_method(self):
print(“Modified”)

MyClass.original_method = new_method
obj = MyClass()
obj.original_method() # Output: “Modified”

86. What is a metaclass in Python?
A metaclass is a class that governs the behavior of other classes. Classes are instances of metaclasses, similar to how objects are instances of classes.
class MyMeta(type):
def __new__(cls, name, bases, attrs):
return super().__new__(cls, name, bases, attrs)

class MyClass(metaclass=MyMeta):
pass

87. What is the difference between __new__() and __init__()?
__new__() creates a new instance of a class, while __init__() initializes the instance after it’s created.

88. How do you find the length of a string in Python?
The len() function can be utilized to determine the length of a string.
s = “Hello”
print(len(s)) # Output: 5

89. What is the locals() function in Python?
locals() returns a dictionary of the current local symbol table, showing all local variables in the current scope.
def my_function():
x = 10
print(locals()) # Output: {‘x’: 10}.

90. What are decorators in Python?
A decorator is a function that takes another function and extends its behavior without modifying it.
def decorator(func):
def wrapper():
print(“Before”)
func()
print(“After”)
return wrapper

@decorator
def say_hello():
print(“Hello”)

say_hello()

91. What are Python iterators and generators?
An iterator is an object that implements the __iter__() and __next__() methods. A generator is a special type of iterator, usually created with a function that uses the yield keyword.

92. Explain __call__() method in Python.
The __call__() method makes an instance of a class callable like a regular function.

Scroll to Top