Top Python Interview Questions & Answers


1. What is Python, and what are its key features?

Python is a high-level, open-source, general purpose and interpreted programming language known for its simplicity, readability, and versatility. Its key features include dynamic typing, automatic memory management, and has an extensive standard library.

2. How do you comment in Python?

In Python, comments are created using the ‘#’ symbol. Anything after ‘#’ on the same line is considered a comment. This approach is used to comment a single line in Python.

#This is a single-line comment

3. What is PEP 8?

PEP 8 is the Python Enhancement Proposal that provides coding conventions for writing clean and readable Python code. It contains the guidelines and best practices that should be followed while writng Python code.

4. How do you check the version of Python installed on your system?

You can check the Python version by opening a terminal or command prompt and typing python --version or python -V. OR if we are using some IDE than we can “import sys” and “print(sys.version)”.

5. What are Python’s data types?

Python supports various data types, including int, float, str, list, tuple, dict, set, complex and boolean

6. What is the purpose of the ‘pass’ statement in Python?


The pass statement is a placeholder for a block of code that is not yet written. It does nothing and is used when the syntax requires a statement, but you don’t want to execute any code.

def empty_function():
    pass

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


Lists are mutable (can be modified), whereas tuples are immutable (cannot be changed after creation).

my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_list[0] = 10 # Valid 
my_tuple[0] = 10 # Invalid, will result in error

8. How do you convert a string to an integer in Python?


You can use the int() function to convert a string to an integer. This process is known as Type casting.

num_str = "123"
num_int = int(num_str)

9. What is the use of ‘zip’ in Python?


The zip() is used to combine two or more iterables. I will combine iterables element-wise into tuples. It stops when the shortest iterable is exhausted.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
result = zip(list1, list2)

Output:

[(1, 'a'), (2, 'b'), (3, 'c')]

10. Explain the ‘join’ method in Python.

The join() method is used to concatenate elements of an iterable (e.g., a list) into a single string using a specified separator.

words = ['Hello', 'World', '!']
result = ' '.join(words)

Output

'Hello World !'

11. What is the purpose of the ‘enumerate’ function in Python?

The enumerate() is used to loop over an iterable while keeping track of the index and the element simultaneously.

names = ['Alice', 'Bob', 'Charlie']
for index, name in enumerate(names):
    print(f'Index: {index}, Name: {name}')

Output:

Index: 0, Name: Alice
Index: 1, Name: Bob
Index: 2, Name: Charlie

12. Explain the concept of ‘lambda’ functions in Python.

Lambda functions are anonymous functions defined using the lambda keyword. They are typically used for short, simple operations. Lambda function can have any number of arguments, but only one expression is allowed.

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

Output:

8

13. What is a docstring in Python?

A docstring is a string literal placed as the first statement in a module, class, or function. It is also known as documentation string used for the documentation of the module, class or function.

def my_function():
    """This is a docstring."""
    pass

14. How do you handle exceptions in Python?

In Python, exceptions are handled using the try and except block. It has optional else and finally blocks.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division successful.")
finally:
    print("Execution completed.")

Output:

Cannot divide by zero.
Execution completed.

15. What is the difference between ‘deep copy’ and ‘shallow copy’ in Python?

A shallow copy creates a new object with references to the original objects, while a deep copy creates a new object with copies of the original objects themselves.

import copy

list1 = [1, 2, [3, 4]]
shallow_copy = copy.copy(list1)
deep_copy = copy.deepcopy(list1)

list1[0] = 10
list1[2][0] = 30

print(shallow_copy)
print(deep_copy)

Output:

[1, 2, [30, 4]]
[1, 2, [3, 4]]

16. How do you read a file in Python?

You can use the open() function to open a file and then read its contents using methods like read(), readline(), or readlines().

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

17. What is a decorator in Python?

A decorator is a function that takes another function as an argument and extends the behavior of the latter function without explicitly modifying it.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

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

say_hello()

Output:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

18. What is the purpose of the ‘map’ function in Python?

The map() applies a given function to all items in an iterable and returns a new iterable with the results. Each item of the iterable is sent to the functions as a parameter.

numbers = [1, 2, 3, 4, 5]

def square(x):
    return x ** 2

squares = map(square, numbers)

Output:

[1, 4, 9, 16, 25]

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

You can create a virtual environment using the venv module. For example, in Python 3:

python3 -m venv myenv

20. Explain the usage of the ‘with’ statement in Python.

The with statement is used to ensure that the resources are closed after processing them. We can say that with statement is the shorthand for the try catch block.

with open('example.txt', 'r') as file:
    content = file.read()
# The file is automatically closed outside the 'with' block

21. What are list comprehensions in Python?

List comprehensions are a shorter way to create lists by applying an expression to all the items of an existing iterable.

numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]

Output:

[1, 4, 9, 16, 25]

22. What is a dictionary comprehension in Python?

Dictionary comprehensions are similar to list comprehensions, but they create dictionaries instead of lists. We can say it is a shorter way to create a dictionary by applying an expression to all the items of an existing iterable.

numbers = [1, 2, 3, 4, 5]
squares = {x: x ** 2 for x in numbers}

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

23. Explain the ‘self’ keyword in Python.

The self refers to the instance of a class and is used to access instance variables and methods within the class.

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

    def greet(self):
        print(f"Hello, my name is {self.name}.")

person = Person("Alice")
person.greet()

Output:

Hello, my name is Alice.

24. How do you remove duplicates from a list in Python?

You can convert the list to a set (since sets automatically remove duplicates) and then back to a list.

numbers = [1, 2, 2, 3, 3, 4, 5]
unique_numbers = list(set(numbers))

Output:

[1, 2, 3, 4, 5]

25. What are ‘args’ and ‘kwargs’ in Python?

The *args and **kwargs are used to pass a variable number of arguments to a function. *args represents positional arguments, and **kwargs represents keyword arguments.

def my_function(*args, **kwargs):
    print(args)
    print(kwargs)

my_function(1, 2, 3, name='Alice', age=30)

Output:

(1, 2, 3)
{'name': 'Alice', 'age': 30}

26. How do you handle file I/O in Python?

You can use the open() function to open files in different modes (e.g., read, write, append). Remember to close the file after usage.

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Output:

Hello, World!

27. What are modules in Python?

Modules are files containing Python code that define functions, classes, and variables that can be used in other Python programs.

# mymodule.py
def greeting(name):
    print(f"Hello, {name}!")

# main.py
import mymodule
mymodule.greeting("Alice")

Output:

Hello, Alice!

28. How do you install external packages in Python?

You can use the package manager pip to install external packages. For example, to install the ‘requests’ package: pip install requests.

29. What is a generator in Python?

A generator is a function that can pause its execution and return an intermediate result using the yield keyword. It remembers its state between calls and allows you to iterate over the values one at a time.

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

# Usage
for num in count_up_to(5):
    print(num)

Output:

1, 2, 3, 4, 5

30. Explain the purpose of the ‘sys’ module in Python.

The sys module provides a number of functions and variables used to manipulate the Python runtime environment.

import sys

# Getting the Python version
print(sys.version)

# Exiting the program
sys.exit()

31. What is the use of ‘break’ and ‘continue’ statements in Python?

The break statement is used to terminate a loop prematurely, while the continue statement skips the rest of the loop and moves to the next iteration.

for i in range(1, 6):
    if i == 3:
        break
    print(i)

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1, 2

1, 2, 4, 5

32. Explain the ‘json’ module in Python and its uses.

The json module in Python provides methods to work with JSON (JavaScript Object Notation) data. It can be used to serialize Python objects into JSON strings and deserialize JSON strings into Python objects.

import json

# Serialize Python object to JSON string
data = {'name': 'Alice', 'age': 30}
json_string = json.dumps(data)

# Deserialize JSON string to Python object
data = json.loads(json_string)

33. How do you create a class in Python?

You can create a class using the class keyword, followed by the class name and a colon. The class can have attributes (variables) and methods (functions).

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

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

person = Person("Alice", 30)
person.greet()

Output:

Hello, my name is Alice and I am 30 years old.

34. What is the ‘super()’ function in Python used for?

The super() function is used to call a method from the parent class in a subclass, allowing the subclass to extend or override the behavior of the parent class method.

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

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

child = Child()
child.greet()

Output:

Hello from the Parent class!
Hello from the Child class!

35. Explain the purpose of the ‘os’ module in Python.

The os module provides a way to interact with the operating system, including file operations, directory handling, and environment variables, etc.

import os

# Get the current working directory
current_dir = os.getcwd()

# List all files in a directory
files = os.listdir(current_dir)

36. How do you handle keyword arguments in Python functions?

Python allows defining functions with keyword arguments using the syntax def func(a, b=10, c=20). Keyword arguments allow calling the function with arguments specified by name.

def greet(name, age):
    print(f"Hello, my name is {name} and I am {age} years old.")

greet(name="Alice", age=30)

Output:

Hello, my name is Alice and I am 30 years old.

37. Explain the purpose of the ‘itertools’ module in Python.

The itertools module provides various functions for creating and working with iterators, especially in a memory-efficient way.

import itertools

# Infinite counter
counter = itertools.count(start=1, step=2)
print(next(counter))   
print(next(counter))   

# Iterate over multiple iterables
numbers = [1, 2, 3]
letters = ['a', 'b']
combined = itertools.chain(numbers, letters)
for item in combined:
    print(item)

Output:

1
3
1, 2, 3, 'a', 'b'

38. What is the purpose of the ‘collections’ module in Python?

The collections module provides specialized container data types like namedtuple, defaultdict, deque, Counter, and OrderedDict, which are not available in the built-in types.

import collections

# namedtuple
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
print(p.x, p.y)   

# Output: 1, 2


# defaultdict
fruit_counts = collections.defaultdict(int)
fruit_counts['apple'] += 1
print(fruit_counts['apple'])   

# Output: 1


# deque
queue = collections.deque()
queue.append(1)
queue.append(2)
queue.popleft()
print(queue)   

# Output: deque([2])

39. What is the use of ‘filter()’ function in Python?

The filter() function filters elements from an iterable based on a given test condition. This test condition is defined as the lambda in the below example.

numbers = [1, 2, 3, 4, 5, 6]
is_even = lambda x: x % 2 == 0
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) 

Output:

[2, 4, 6]

40. Explain the ‘is’ and ‘==’ operators in Python.

The ‘==’ operator checks for equality, i.e., if the values of two objects are the same. The ‘is’ operator checks if two objects refer to the same memory location, i.e., if they are the same object.

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2)   # Output: True, as values are equal
print(list1 is list2)   # Output: False, as they are different objects
print(list1 is list3)   # Output: True, as they refer to the same object

Output:

True
False
True

41. Explain the ‘os.path’ module in Python and its uses.

The os.path module provides various functions for working with file paths and directories in a platform-independent way.

import os

# Joining path components
path = os.path.join('dir', 'subdir', 'file.txt')
print("Path =",path)

# Getting the basename and directory name from a path
basename = os.path.basename(path)
dirname = os.path.dirname(path)
print("Basename =",basename)
print("Dirname =", dirname)

Output:

Path = dir\subdir\file.txt
Basename = file.txt
Dirname = dir\subdir

42. What is the purpose of the ‘re’ module in Python?

The re module provides support for regular expressions in Python, allowing you to search, match, and manipulate strings using pattern-matching.

import re

text = "Hello, my name is Alice. I live in Wonderland."
pattern = r'\b[A-Z][a-z]+\b'
result = re.findall(pattern, text)
print(result)   

Output:

['Hello', 'Alice', 'Wonderland']

43. Explain the purpose of the ‘datetime’ module in Python.

The datetime module provides classes for manipulating dates and times in Python.

import datetime

# Getting the current date and time
now = datetime.datetime.now()

# Formatting dates as strings
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_date)

Output:

2023-10-03 19:58:04

44. How do you sort a list in Python?

You can use the sorted() function to sort a list or the list.sort() method to sort the list in place.

numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers)
print("Sorted function  =",sorted_numbers)

# Sorts the list in place
numbers.sort() 
print("In Place Sorting =",numbers)

Output:

Sorted function  = [1, 2, 3, 4, 5]
In Place Sorting = [1, 2, 3, 4, 5]

45. Explain the purpose of the ‘random’ module in Python.

The random module provides functions for generating random numbers, shuffling sequences, and choosing random elements.

import random

# Generating a random integer between a range
random_number = random.randint(1, 100)
print("Random Number =",random_number)

# Shuffling a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print("Shuffled List=",numbers)

Output:

Random Number = 20
Shuffled List= [2, 3, 5, 1, 4]

46. What is a context manager in Python?

A context manager is an object that defines methods __enter__() and __exit__(). It is used with the with statement to set up and clean up resources automatically.

47. Explain the purpose of the ‘logging’ module in Python.

The logging module provides a flexible framework for emitting log messages from Python programs. It allows developers to control the level, format, and destination of log messages.