Python Interview Questions

Here are the top 50 commonly asked questions in Python interviews. Whether you’re just starting your preparation or need a quick refresher, these questions and answers will help you tackle your interview with confidence.

Basic Python Interview Questions with Answers

1. What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

2. What are the key features of Python?

Some key features of Python include its simplicity, readability, dynamic typing, automatic memory management (garbage collection), extensive standard library, and support for multiple programming paradigms.

3. How do you comment in Python, and why is it important?

In Python, you can use the # symbol to add comments. Comments are important for documenting code, making it easier for others (or your future self) to understand the purpose and functionality of different parts of the code.

4. What is PEP 8, and why is it important in Python development?

PEP 8 is the Python Enhancement Proposal that provides guidelines for writing Python code in a consistent and readable manner. Following PEP 8 ensures that your code is more maintainable and understandable, especially when working in teams or collaborating on projects.

5. What are the different data types in Python?

Python supports various data types, including integers, floating-point numbers, strings, lists, tuples, dictionaries, sets, and booleans.

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


A list is mutable, meaning its elements can be modified after it is created, while a tuple is immutable, meaning its elements cannot be changed after creation. Lists are created using square brackets [], and tuples are created using parentheses ().

7. How do you define a function in Python?

In Python, you can define a function using the def keyword followed by the function name and parameters, if any. For example:

def greet(name):
    print("Hello, " + name)

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

The == operator compares the values of two objects, while the is operator checks if two variables refer to the same object in memory. For example:

x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)  # True, because the values are the same
print(x is y)  # False, because they are different objects

9. What is a module in Python?

A module in Python is a file containing Python code. It can define functions, classes, and variables. You can use the import statement to import and use modules in your Python programs.

10. How do you handle exceptions in Python?

Exceptions in Python can be handled using the try, except, else, and finally blocks. The try block contains the code that might raise an exception, and the except block handles the exception if it occurs. The else block is executed if no exception occurs, and the finally block is always executed, regardless of whether an exception occurs or not. For example:

    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero!")
    print("Result:", result)
    print("This will always execute.")

11. What are Python decorators?

Python decorators are functions that modify the behavior of other functions or methods. They allow you to add functionality to existing functions dynamically without modifying their code. Decorators are often used for tasks such as logging, authentication, and memorization.

12. Explain the difference between ‘deep copy’ and ‘shallow copy’ in Python.


A shallow copy creates a new object but does not recursively copy the objects contained within it. Changes made to the original object may affect the copied object. A deep copy, on the other hand, creates a new object and recursively copies all objects contained within it, resulting in two independent objects.

13. What are lambda functions in Python?

Lambda functions, also known as anonymous functions, are small, inline functions defined using the ‘lambda’ keyword. They can take any number of arguments but can only have a single expression. Lambda functions are often used for simple operations where defining a separate function would be overkill.

14. Explain the difference between append() and extend() methods in Python lists.

The append() method adds a single element to the end of a list, while the extend() method adds multiple elements, such as another list, to the end of a list.

15. What is the purpose of __init__ method in Python classes?

The __init__ method is a special method in Python classes used for initializing new instances of the class. It is called automatically when a new object is created and allows you to initialize attributes and perform any necessary setup.

16. Explain the use of super() function in Python.

The super() function is used to call methods and access attributes from the parent class within a subclass. It is often used in method overriding to invoke the superclass’s method while extending its behavior.

17. What is the role of the global keyword in Python?


The global keyword in Python is used inside functions to indicate that a variable refers to a global variable rather than a local one. Without the global keyword, variables assigned inside a function are by default considered local to that function’s scope.

18. Explain the purpose of the with statement in Python.

The with statement in Python is used to wrap the execution of a block of code with methods defined by a context manager. It ensures that resources are properly managed and cleaned up, even if exceptions occur, by automatically invoking the __enter__() and __exit__() methods of the context manager.

19. What is a dictionary in Python?

A dictionary is an unordered collection of key-value pairs. Each key-value pair maps the key to its associated value. Dictionaries are defined using curly braces {}.

20. Explain the concept of indentation in Python.

Indentation is a significant aspect of Python syntax used for structuring code blocks. Unlike other programming languages that use braces {} or keywords like begin and end to denote blocks, Python uses indentation to define the scope of code blocks.

Intermediate Python Interview Questions with Answers

21. What is a Python package?

A Python package is a directory containing Python modules and an optional file, used for organizing and distributing code.

22. What are strings in Python, and how are they represented?

Strings in Python are sequences of characters, represented using single quotes (‘), double quotes (“), or triple quotes (”’ or “””). Example: “Hello”.

23. What is a tuple in Python?

A tuple in Python is a data structure that stores an ordered collection of elements. It is similar to a list but immutable, meaning its elements cannot be changed after creation.

24. What is a set in Python?

A set in Python is a collection of unique elements with no specific order.

25. What are built-in functions in Python?

Built-in functions are functions that are predefined in Python and can be used without importing any module.

26. What is a class in Python?

A class in Python is a blueprint for creating objects. It defines properties and behaviors that all objects of that class will have.

27. What are files in Python?

Files in Python are objects that allow us to interact with external files on our computer’s storage. They are used for reading from and writing to files.

28. What are the different modes in which you can open a file in Python?

There are several modes for opening files in Python:

  • “r”: Read mode (default).
  • “w”: Write mode, truncating the file first.
  • “a”: Append mode, appending to the end of the file if it exists.
  • “b”: Binary mode, for binary files.
  • “+”: Update mode, for both reading and writing.

29. What is object-oriented programming (OOP) in Python?

Object-oriented programming is a programming paradigm that revolves around the concept of objects. It emphasizes the organization of code into classes and objects, encapsulation, inheritance, and polymorphism.

30. What are some popular Python libraries and frameworks, and their uses?

Popular Python libraries and frameworks include NumPy, Pandas, and Matplotlib, commonly used for data manipulation, analysis, and visualization tasks. Another widely-used framework is Django, which simplifies web development by providing tools for authentication, routing, and database management. For machine learning tasks, Scikit-learn and TensorFlow are popular choices, offering comprehensive tools for classification, regression, and deep learning models.

31. Explain the concept of garbage collection in Python.

Garbage collection in Python is an automatic process that reclaims memory occupied by objects no longer in use, preventing memory leaks and ensuring efficient memory usage. It automatically deallocates memory when objects are no longer needed, reducing the burden on programmers to manage memory manually.

32. What are the assignment operators in Python?

Assignment operators in Python include =, +=, -=, *=, /=, //=, %=, **=, which are used to assign values and perform arithmetic operations simultaneously.

33. Explain the difference between integers and floats in Python.

Integers are whole numbers without any decimal point, while floats are numbers with decimal points or numbers in scientific notation.

34. What are bitwise operators in Python?

Bitwise operators in Python include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift), which are used to perform operations on individual bits of integers.

35. What is list comprehension in Python?

List comprehension is a concise and efficient way to create lists in Python by applying an expression to each item in an iterable and filtering elements based on a condition.

36. What is a list in Python?

A list in Python is a mutable, ordered collection of elements enclosed within square brackets []. It can contain elements of different data types and supports indexing and slicing operations.

37. What are the advantages of using Python over other programming languages?

Some key advantages of using Python over other programming languages include its readability, versatility across various domains, extensive standard library, strong community and ecosystem, platform independence, scalability, integration capabilities, and ease of learning.

38. What are conditional statements in Python, and how do you use them?

Conditional statements in Python, such as if, elif, and else, enable the execution of different code blocks based on specified conditions. They are used by defining conditions after if or elif, followed by the code to execute if the condition is true. The else statement, which is optional, is executed if none of the previous conditions are met.

39. Explain the differences between Python 2 and Python 3.

Python 2 and Python 3 have differences in syntax and behavior. For instance, Python 3 requires parentheses for print(), always returns a float in division, and defaults to Unicode for strings. Built-in functions may return views instead of lists in Python 3, enhancing performance. Python 3 also enforces stricter handling of exceptions and Unicode compared to Python 2.

40. What are variables in Python?

Variables in Python are symbolic names that represent values stored in memory.

41. How do you define inheritance in Python?

In Python, inheritance is achieved by specifying the base class(es) in parentheses after the name of the derived class during its definition using the syntax class DerivedClassName(BaseClassName).

Python Programming Interview Questions with Answers

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

x = 5
y = 2
print(x * y)

Answer: 10

Explanation: The code multiplies the values of variables x and y, resulting in 10 (5 * 2), which is then printed.

43. What does the following code snippet do?

def factorial(n):
    if n == 0:
        return 1
        return n * factorial(n-1)
num = 5

Answer: 120

Explanation: The factorial() function calculates the factorial of a given number n recursively. If n is equal to 0, it returns 1 (base case). Otherwise, it returns n multiplied by the factorial of n-1. In this case, num is assigned the value 5, and the factorial of 5 is calculated and printed.

44. What will be the output of the following code snippet?

x = 10
y = 20
x, y = y, x
print(x, y)

Answer: 20 10

Explanation: The code swaps the values of variables x and y using tuple unpacking. After the assignment x, y = y, x, the value of x becomes 20 and the value of y becomes 10, resulting in the printed output 20 10.

45. What will be the output of the following code snippet?

nums = [1, 2, 3, 2, 1, 4, 5, 4]
unique_nums = []
for num in nums:
    if num not in unique_nums:

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

Explanation: The code iterates through the list nums and appends each unique element to the list unique_nums. Finally, it prints the list unique_nums, containing only the unique elements from nums.

46. What will be the output of the following code snippet?

x = 5
print(x ** 3)

Answer: 125

Explanation: The code calculates the cube of the variable x using the exponentiation operator **, resulting in 125 (5 raised to the power of 3).

47. What is the output of the following code snippet?

my_tuple = (1, 2, 3)
a, b, c = my_tuple

Answer: 2

Explanation: The tuple my_tuple contains elements (1, 2, 3). Using tuple unpacking, the variables a, b, and c are assigned the values of the tuple elements. Since b corresponds to the second element of the tuple, which is 2, it is printed.

48. What will be the output of the following code snippet?

my_list = [1, 2, 3]

Answer: [1, 2, 3, 4]

Explanation: The append() method adds the element 4 to the end of the list my_list, resulting in the modified list [1, 2, 3, 4], which is then printed.

49. What is the output of the following code snippet?

my_set = {1, 2, 3, 4, 5}

Answer: 6

Explanation: The add() method adds the element 6 to the set my_set, increasing its length to 6, which is then printed.

50. What is the output of the following code snippet?

my_set = {1, 2, 3, 4, 5}

Answer: 4

Explanation: The discard() method removes the element 3 from the set my_set. Since the set initially contained five elements and one element was removed, the length of the set becomes 4, which is then printed.

Useful Resources:

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.