150 Python Interview Questions You Should Know in 2024

So you have a Python interview coming up or you are interested in positions that require you to be a hotshot at Python? Maybe you are just a curious bird like me and looking for python interview questions to sharpen your coding skills. Whatever it is, you are at the right place. Because in this post I will list not just 10, 20 or 30 but 150 Python interview questions and their answers that are packed to help you ace your next Python interview.

1. What is Python?

Python is a high-level, interpreted, general-purpose programming language known for its simplicity and readability.

You may like: The Ultimate Python Cheat Sheet – An Essential Reference for Python Developers

2. Who created Python, and what language did it succeed?

Python was created by Guido van Rossum in 1991. It is the successor of the ABC programming language, which inspired its design.

3. Is Python compiled or interpreted?

Python is an interpreted language, meaning it executes code line by line, making it easy to debug.

4. What are some key features of Python?

  • User-friendly syntax.
  • Object-oriented.
  • Dynamically typed.
  • Portable and platform independent.
  • Extensive standard library.

5. How is Python’s syntax different from Java’s?

Python uses indentation to define code blocks, whereas Java relies on curly braces {}. This makes Python more readable and concise.

6. What’s the difference between a list and a tuple in Python?

Lists are mutable (modifiable), while tuples are immutable (non-modifiable). Lists use square brackets [] and tuples use parentheses (). Tuples are generally faster and more memory-efficient than lists.

7. Explain local and global variables in Python.

  • Local variables: Declared inside a function and accessible only within that function.
  • Global variables: Declared outside any function and accessible throughout the program.

8. What is type conversion? Name some methods used in Python.

Type conversion refers to converting one data type to another. Common methods include:

  • int()
  • float()
  • str()
  • tuple()
  • list()
  • set()

9. How do you create a function in Python?

Functions in Python are created using the def keyword:

def greet():
    print("Hello, World!")

10. What is a default argument?

A default argument is a predefined value assigned to a function parameter. If no value is passed during the function call, the default value is used.

11. What are anonymous functions in Python?

Anonymous functions, also known as lambda functions, are single-expression functions defined using the lambda keyword.

add = lambda x, y: x + y
print(add(5, 3))

Output: 8

12. Name two other scopes in Python apart from local and global.

  • Module-level scope: Variables accessible throughout the module.
  • Built-in scope: Contains Python’s built-in functions like print() and len().

13. What are Python’s built-in collections?

  • List
  • Tuple
  • Set
  • Dictionary

14. How do you comment on a single line in Python?

Use the # symbol:

# This is a single-line comment

15. How do you comment on multiple lines in Python?

Use triple quotes ”’ ”’:

'''
This is a multi-line comment.
It spans multiple lines.
'''

16. Write a loop to iterate over a list in Python.

my_list = [1, 2, 3, 4]
for item in my_list:
    print(item)

17. What’s the difference between break and continue?

  • break: Terminates the loop entirely.
  • continue: Skips the rest of the current iteration and moves to the next.

18. What is the pass statement in Python?

The pass statement acts as a placeholder and does nothing when executed. Unlike comments, it’s required for code structure in some places.

19. What is a dictionary in Python?

my_dict = {"name": "Alice", "age": 25}

20. Which Python collection does not allow duplicate values?

Sets do not allow duplicate values.

21. How do you check if a string starts with a capital letter in Python?

Use the istitle() method:

print("Hello World".istitle())

Output: True

22. How do you check if a substring exists in a string?

Use the in operator:

text = "Welcome to Python programming."
print("Python" in text)

Output: True

Read: An Essential Guide to Python Text Editing & Processing

23. What built-in function is used to check the length of a string?

The len() function is used to determine the length of a string.

text = "Python"
print(len(text))

Output: 6

24. How do you convert a string into a list?

Use the split() method to break a string into a list of substrings.

text = "Python is amazing"
words = text.split()
print(words)

Output: [‘Python’, ‘is’, ‘amazing’]

25. Write a Python code snippet to reverse a string.

text = "Python"
reversed_text = text[::-1]
print(reversed_text)

Output: nohtyP

26. What happens when you add a string and an integer in Python?

It raises a TypeError because Python does not allow implicit type conversion between strings and integers.

result = "Python" + 123 

Output: TypeError

27. How do you check if all characters in a string are uppercase?

Use the isupper() method.

text = "PYTHON"
print(text.isupper())

28. What is the difference between range() and xrange()? in a string are uppercase?

  • range(): Returns a list in Python 2 and a range object in Python 3.
  • xrange(): Only available in Python 2, it returns an xrange object that generates numbers on the fly (memory-efficient).

29. Name some immutable types in Python.

  • Tuple
  • String
  • Number (int, float)

30. Name some mutable types in Python.

  • List
  • Set
  • Dictionary

31. What is a lambda function in Python?

A lambda function is a small, anonymous function that can take multiple arguments but only contains a single expression.

square = lambda x: x * x
print(square(4))

Output: 16

32. How do you write a lambda function in Python?

add = lambda x, y: x + y
print(add(3, 7))

Output: 10

33. How many types of loops are available in Python?

Python supports two types of loops:

  • for loop
  • while loop

You may like: Loops in Python – The Ultimate Tutorial for Beginners

34. What will the following code output?

numbers = [1, 2, 3, 4, 5]
print(numbers[:-3])

Output: [1, 2]

35. What will the following code output?

numbers = [1, 2, 3, 4, 5]
print(numbers[:])

Output: [1, 2, 3, 4, 5]

36. What are Python modules?

Python modules are files containing Python code (functions, classes, or variables) that can be reused in other Python programs.

37 Name some common built-in Python modules.

  • os
  • sys
  • math
  • random
  • json

38. How do you import a specific attribute from a module?

Use the from module import attribute syntax.

from math import sqrt
print(sqrt(16))

Output: 4.0

39. Can you write Python code without indentation?

No, Python strictly enforces indentation to define code blocks. Without it, the code will throw an IndentationError.

40. What’s the difference between Python arrays and lists?

  • Arrays: Can only store elements of the same data type.
  • Lists: Can store elements of different data types.
import array as arr
numbers = arr.array("i", [1, 2, 3])

41. How do you create an array in Python?

Use the array module to create an array.

import array as arr
my_array = arr.array("i", [1, 2, 3])
print(my_array)

Output: array(‘i’, [1, 2, 3])

42. What will be the output of the following code?

s = {1, 1, 1, 1}
print(s)

Output: {1}

Explanation: Sets in Python do not allow duplicate values.

43. Can you create an empty set using {}?

No, using {} creates an empty dictionary. To create an empty set, use the set() function:

empty_set = set()
print(type(empty_set))

Output: <class ‘set’>

44. What is the purpose of the set() function?

The set() function creates a set, which is an unordered collection of unique elements.

45. Which Python collection is used for operations like union, intersection, and difference?

Sets are used for these operations.

a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))  # Output: {1, 2, 3, 4, 5}

Output: {1, 2, 3, 4, 5}

46. Does Python support object-oriented programming?

Yes, Python supports object-oriented programming with features like classes, inheritance, and polymorphism.

47. What is __init__ in Python?

class Person:
    def __init__(self, name):
        self.name = name

48. What is the purpose of the self keyword in Python?

The self keyword represents the instance of a class. It is used to access attributes and methods within the class.

49. Is it necessary to use self in a class?

Yes, it is necessary to use self in instance methods to refer to the current object.

50. What is a class attribute?

A class attribute is shared across all instances of a class. It is defined outside the methods and belongs to the class rather than an instance.

51. Does Python support inheritance?

Yes, Python supports inheritance, including single, multiple, and multilevel inheritance.

52. What is the purpose of the super() method?

The super() method allows access to methods in a parent class.

class Parent:
    def greet(self):
        print("Hello from Parent")

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

53. What does the is operator do in Python?

The is operator checks if two variables point to the same object in memory.

a = [1, 2]
b = [1, 2]
print(a is b)

Output: False

54 How do you work with dates and times in Python?

Use the datetime module.

import datetime
now = datetime.datetime.now()
print(now)

Output: It should print the current date and time.

55. What does it mean that Python is dynamically typed?

It means variables in Python do not need explicit declaration of their type. The type is determined during runtime.

56. Are Python functions first-class objects?

Yes, Python functions are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions.

57. How do you reverse an array in Python?

import array as arr
my_array = arr.array('i', [1, 2, 3, 4])
print(my_array[::-1])

Output: array(‘i’, [4, 3, 2, 1])

58. What are *args used for in Python?

The *args syntax allows a function to accept a variable number of positional arguments.

def greet(*names):
    for name in names:
        print(f"Hello, {name}")
greet("Alice", "Bob", "Charlie")

59. How do you split a string into a list in Python?

Use the split() method.

text = "Python is great"
words = text.split()
print(words)  # Output: ['Python', 'is', 'great']

Output: [‘Python’, ‘is’, ‘great’]

60. How do you check if a given string is a palindrome?

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("madam"))  
print(is_palindrome("hello"))

Output: It should print True for the first print() statement and False for the second.

61. How do you remove vowels from a string in Python?

def remove_vowels(s):
    vowels = "aeiouAEIOU"
    return ''.join([char for char in s if char not in vowels])

print(remove_vowels("Python"))

Output: Pythn

62. Can you pass one function as an argument to another function in Python?

Yes, since Python functions are first-class objects, you can pass one function as an argument to another.

63. What are docstrings in Python?

Docstrings are string literals used to document a function, class, or module. They are written using triple quotes.

def greet():
    """This function greets the user."""
    print("Hello!")

64. How can you access a function’s docstring?

Use the __doc__ attribute.

def greet():
    """This function greets the user."""
    pass

print(greet.__doc__)

Output: This function greets the user.

65. What’s the difference between a comment and a docstring?

  • Comments are ignored by Python and cannot be accessed during runtime.
  • Docstrings are used to document code and can be accessed using the __doc__ attribute.

66. Does Python support multiple inheritance?

Yes, Python supports multiple inheritance.

class A:
    pass

class B:
    pass

class C(A, B):
    pass

67. How do you create an empty class in Python?

Use the pass statement:

class EmptyClass:
    pass

68. What are the different types of functions in Python?

  • Built-in functions (e.g., len(), print())
  • User-defined functions

69. What types of operators are available in Python?

  • Arithmetic operators
  • Logical operators
  • Comparison operators
  • Bitwise operators
  • Assignment operators
  • Identity operators

70. Where can Python be used?

Python is used in various domains, including:

  • Web development
  • Data science
  • Machine learning
  • Artificial intelligence
  • Game development

71. What is Django?

Django is a high-level Python web framework that enables rapid development of secure and maintainable websites.

Also read: Django vs. Flask in 2024 – Choosing the Right Web Framework

72. What are some key features of Django?

  • Built-in authentication system
  • URL routing
  • ORM (Object-Relational Mapper)
  • Template engine
  • Built-in admin interface

73. Can Django be used for backend development?

Yes, Django is primarily used for backend development, offering powerful tools for handling server-side logic and database operations.

74. Name some databases supported by Django.

  • SQLite
  • MySQL
  • PostgreSQL
  • Oracle

75. What architectural pattern does Django follow?

Django follows the Model-View-Template (MVT) architectural pattern.

76. What are the advantages of using Django?

  • Easy to learn and use.
  • Secure by default.
  • Scalable for large applications.
  • Extensive community support.
  • Reduces development time.

77. What are the disadvantages of using Django?

  • Overhead for small applications.
  • Limited flexibility in ORM.
  • Can be bulky for simple projects.

78. What are Django signals?

Django signals allow certain senders to notify listeners when specific events occur.

79. Name two key parameters used in Django signals.

  • Sender: The model or function that sends the signal.
  • Receiver: The function or method that listens to the signal.

80. What is a Django session?

A Django session allows storing user-specific data, such as login information, on the server side.

81. What is the role of Django views?

Django views handle user requests, process data from models, and return responses to templates for rendering.

82. How do Django views work with models and templates?

  • Models: Fetch data from the database.
  • Views: Process the data and pass it to templates.
  • Templates: Display the processed data in a user-friendly format.

83. What is Flask?

Flask is a microframework written in Python that is lightweight and ideal for small applications or prototyping.

RelatedBuilding a Web App with Python – Getting Started With Flask

84. How can Flask send emails?

Flask can send emails using the flask-mail extension, which integrates email-sending functionality.

85. Why is Flask called a microframework?

Flask is termed a microframework because it provides only core functionalities, such as routing and request handling, while additional features are implemented via extensions

86. How do you add ORM functionality to Flask?

Use the Flask-SQLAlchemy extension to integrate an ORM with Flask applications.

87. What are the advantages of using Flask?

  • Lightweight and flexible
  • Easy to learn for beginners
  • Supports extensions for added functionality
  • Comes with a built-in development server

88. How do you differentiate between Django and Flask?

  • Django: A full-stack framework suited for large applications.
  • Flask: A microframework ideal for smaller applications and prototyping.

89. What are iterators in Python?

Iterators are objects in Python that allow traversing through elements, one at a time, using the __next__() method.

90. Which method is used to create custom iterators in Python?

The __iter__() method is used to initialize the iterator, and the __next__() method is used to iterate through elements.

91. What happens at the end of an iterator?

A StopIteration exception is raised when there are no more elements to traverse.

92. What are Python generators?

Generators are a special type of iterator that allows generating items lazily using the yield keyword instead of storing them in memory.

93. Write a simple Python generator example.

def generate_numbers():
    for i in range(3):
        yield i

for number in generate_numbers():
    print(number)

94. What is the difference between yield and return?

  • return: Terminates the function and returns a value.
  • yield: Pauses the function, saving its state, and resumes on the next call.

95. Do generators automatically implement __iter__() and __next__()?

Yes, Python generators automatically implement these methods, making them easier to use than custom iterators.

96. Can you create a generator without using yield?

No, the yield keyword is mandatory for defining a generator.

97. What are Python decorators?

Decorators are functions in Python that modify the behavior of another function or method. They are often used for logging, validation, or access control.

98. Write an example of a Python decorator.

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

99. How do you use regular expressions in Python?

Import the re module to work with regular expressions.

import re
pattern = r"\d+"
match = re.search(pattern, "There are 123 apples")
print(match.group())  # Output: 123

Output: 123

100. What does the * signify in regular expressions?

The * matches zero or more occurrences of the preceding character or group.

Congrats if you made it this far in the guide! We are almost there. 😉

101. Is Python 2 still supported?

No, Python 2 reached its end of life on January 1, 2020, and is no longer officially supported.

102. What is PEP 8?

PEP 8 is the official Python style guide that provides conventions for writing clean, readable code.

103. How does Python manage memory?

Python manages memory using:

  • A private heap space for all objects and data structures.
  • An in-built garbage collector to reclaim unused memory.

104. What is slicing in Python?

Slicing allows you to extract a portion of a sequence (e.g., list, string) using a specified range of indices.

my_list = [0, 1, 2, 3, 4]
print(my_list[1:4])  # Output: [1, 2, 3]

Output: [1, 2, 3]

105. How do you copy an object in Python?

Use the copy() or deepcopy() method from the copy module.

106. What is the Pyramid framework used for?

Pyramid is a Python web framework designed for building large, complex web applications.

107. What are the limitations of Python?

  • Slower compared to compiled languages like C++.
  • Limited for mobile development.
  • GIL (Global Interpreter Lock) can be a bottleneck for multithreaded applications.

108. How do you remove duplicate values from a list in Python?

my_list = [1, 2, 2, 3, 4, 4]
unique_list = list(set(my_list))
print(unique_list)

Output: [1, 2, 3, 4]

110. What is the purpose of the ** operator?

The ** operator is used for exponentiation.

print(2 ** 3)  

Output: 8

110. What are membership operators in Python?

  • in: Checks if a value exists in a sequence. –
  • not in: Checks if a value does not exist in a sequence.

111. What is raw_input() in Python?

raw_input() is used in Python 2 to take user input as a string. In Python 3, it has been replaced with input().

112. Which Python collection is most similar to JavaScript objects?

A dictionary in Python is similar to JavaScript objects, as both store key-value pairs.

113. Why is Python often recommended for beginners?

  • Simple and readable syntax.
  • Extensive standard library.
  • Versatile for various use cases.
  • Dynamically typed.

114. What’s the difference between Python and Java?

  • Typing: Python is dynamically typed, while Java is statically typed.
  • Syntax: Python uses indentation for blocks, while Java uses curly braces {}.
  • Speed: Java is faster due to its compiled nature, whereas Python is interpreted.

115. Explain the following code snippet.

a, b, c = 1, 2, 3

Answer: The code initializes three variables a, b, and c with the values 1, 2, and 3, respectively.

116. What does the following code do?

a = b = c = 1

Answer: All three variables a, b, and c are assigned the same value of 1.

117. What is the with statement in Python used for?

The with statement is used for resource management, such as opening files. It ensures that resources are properly released, even if an error occurs.

with open("file.txt", "r") as file:
    content = file.read()

118. What does the global keyword do?

The global keyword allows modification of a variable declared in the global scope from within a function.

x = 5

def modify_global():
    global x
    x = 10

modify_global()
print(x)

Output: 10

119. What will the following code output?

print(['Python'] * 2)

Answer: [‘Python’, ‘Python’]

Explanation: The multiplication operator repeats the elements of the list.

120. What is pickling in Python?

Pickling is the process of serializing a Python object into a byte stream using the pickle module.

import pickle

data = {"key": "value"}
with open("data.pkl", "wb") as file:
    pickle.dump(data, file)

121. What is unpickling?

Unpickling is the reverse process of converting a byte stream back into a Python object using the pickle module.

with open("data.pkl", "rb") as file:
    data = pickle.load(file)
print(data)

Output: {‘key’: ‘value’}

122. Does Python pass arguments by value or reference?

Python uses pass-by-object-reference, meaning that mutable objects can be modified inside a function, while immutable objects cannot.

123. Is Python case-sensitive?

Yes, Python is case-sensitive, meaning variable names like Var and var are treated as distinct.

125. What will be the output of this code?

l = [1, 2, 3, 4, 5]
print(l[10:])

Answer: An empty list []

Explanation: Slicing a list beyond its range does not raise an error but returns an empty list.

126. What types of databases are supported by Python?

Python supports both SQL and NoSQL databases, including:

  • SQL: MySQL, PostgreSQL, SQLite
  • NoSQL: MongoDB, Cassandra

127. Can Python code written on Windows run on Linux?

Yes, Python code is cross-platform and can run on different operating systems without modification, provided the required dependencies are available.

128. What happens when you execute the following code?

f = open("new.txt", "w")

Answer: It opens the file new.txt for writing. If the file does not exist, it creates it. If it exists, its content is overwritten.

129. When is the ZeroDivisionError exception raised?

This exception is raised when a division or modulo operation has a denominator of zero.

130. What’s the difference between abs() and math.fabs()?

  • abs(): A built-in function that works with integers, floats, and complex numbers.
  • math.fabs(): Part of the math module and works only with floats.

131. What does the -1 index signify in a sequence?

l = [10, 20, 30]
print(l[-1])  

Output: 30

132. What is a Python module?

A Python module is a file containing Python code (functions, classes, or variables) that can be reused in other programs.

133. How do you import a module in Python?

Use the import statement:

import math
print(math.sqrt(16))

Output: 4.0

134. Can you create custom modules in Python?

Yes, you can create a custom module by saving Python code in a .py file and importing it into other scripts.

135. What is the dir() function used for?

The dir() function is used to display the attributes and methods of an object.

136. How do you check the type of a variable in Python?

Use the type() function:

x = 10
print(type(x))

Output: <class ‘int’>

137. How do you handle exceptions in Python?

Use try-except blocks:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

138. What is the difference between is and == in Python?

  • is: Checks if two variables point to the same object in memory. –
  • ==: Checks if two variables have the same value.

139. What is Python’s GIL?

The Global Interpreter Lock (GIL) is a mutex in CPython that allows only one thread to execute Python bytecode at a time, limiting multi-threading capabilities.

140. How do you create a virtual environment in Python?

Use the venv module:

python -m venv myenv

Activate it using:

  • Windows: myenv\Scripts\activate
  • Linux/Mac: source myenv/bin/activate

141. How do you list all installed Python packages?

Use the pip list command in the terminal to display all installed Python packages and their versions.

pip list

142. How do you install a specific version of a Python package?

Use the pip install command with the package name and version:

pip install package_name==1.2.3

143. What is a namespace in Python?

A namespace is a container that holds identifiers (variable names, function names, etc.) and maps them to their corresponding objects.

144. What are Python’s built-in data types?

  • Numeric types: int, float, complex
  • Sequence types: list, tuple, range
  • Text type: str
  • Mapping type: dict
  • Set types: set, frozenset
  • Boolean type: bool

145. What is the purpose of the enumerate() function in Python?

The enumerate() function adds a counter to an iterable and returns it as an enumerate object.

colors = ["red", "blue", "green"]
for index, color in enumerate(colors):
    print(index, color)

Output: 0 red 1 blue 2 green

146. What is the difference between deepcopy() and copy()?

  • copy(): Creates a shallow copy of an object, which copies the object but not nested objects.
  • deepcopy(): Creates a deep copy of an object, including all nested objects.

147. What are Python’s file handling modes?

  • “r”: Read mode
  • “w”: Write mode (overwrites file)
  • “x”: Create mode (fails if the file exists)
  • “a”: Append mode
  • “b”: Binary mode
  • “t”: Text mode

148. What is a Python metaclass?

A metaclass is a class of a class. It defines how classes behave and can be used to control class creation.

149. How do you create a thread in Python?

Use the threading module:

import threading

def task():
    print("Thread is running")

t = threading.Thread(target=task)
t.start()

150. What are f-strings in Python?

F-strings, introduced in Python 3.6, provide a concise and efficient way to format strings.

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Conclusion

Phew! That was a lot to digest I assume. But you made it to the end.

via GIPHY

Preparing for an interview can feel overwhelming. And with these 150 Python interview questions. you have a solid resource to help you with the most commonly asked Python interview questions.

Remember, to practice each question thoroughly. I also have other guides and tutorials on my website, so feel free to go over them to help you better understand some of the concepts.

What other python interview questions can you think of? Let’s discuss below!

Leave a Reply