0% found this document useful (0 votes)
28 views

Python Interview Questions and Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Python Interview Questions and Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Interview Questions and

Answers
Subjective Questions:-

1. What is Python? What are its key features?


- Python is a high-level, interpreted programming language known for its simplicity and
readability. Key features include dynamic typing, automatic memory management, a large
standard library, and support for multiple programming paradigms.

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


- Python 2 is legacy and Python 3 is the current version. Python 3 was designed to fix issues
and inconsistencies in Python 2, such as Unicode handling, print statement syntax, and integer
division behavior.

3. What are the advantages of using Python?


- Advantages of Python include its simplicity, readability, versatility, extensive standard library,
and strong community support.

4. How is memory managed in Python?


- Python uses automatic memory management through garbage collection. Objects that are
no longer referenced are automatically deallocated.

5. Explain the concept of Python's Global Interpreter Lock (GIL).


- GIL is a mutex that protects access to Python objects, preventing multiple native threads
from executing Python bytecodes simultaneously. This can limit the concurrency of multi-
threaded Python programs.

6. What are Python decorators and how do they work?


- Decorators are functions that modify the behavior of other functions or methods. They allow
adding functionality to existing code without modifying its structure. They are implemented using
the `@decorator_name` syntax.

7. Differentiate between list and tuple in Python.


- Lists are mutable, ordered collections of elements, while tuples are immutable, ordered
collections. Lists are defined with square brackets `[ ]`, and tuples are defined with parentheses
`( )`.

8. What is PEP 8? Why is it important?


- PEP 8 is the style guide for Python code. It defines coding conventions to ensure consistent
and readable code across projects. Following PEP 8 improves code quality and maintainability.
9. How does Python handle exceptions?
- Python uses try-except blocks to handle exceptions. Code that might raise an exception is
placed inside a try block, and handling code is placed in except blocks.

10. What are the different ways to handle exceptions in Python?


- Exceptions can be handled using try-except blocks, try-except-else blocks (to execute
code when no exception occurs), and try-except-finally blocks (to execute cleanup code
regardless of whether an exception occurs).

11. Explain the difference between `__str__()` and `__repr__()` methods.


- `__str__()` is used to return a human-readable string representation of an object, while
`__repr__()` is used to return a string representation of the object that is as unambiguous as
possible and should be able to recreate the object when passed to `eval()`.

12. What is the purpose of the `__init__()` method in Python classes?


- `__init__()` is a special method in Python classes used for initializing newly created
objects. It is called automatically when a new instance of the class is created.

13. What is the difference between `append()` and `extend()` methods in Python lists?
- `append()` is used to add a single element to the end of a list, while `extend()` is used
to add multiple elements (such as elements of another list) to the end of a list.

14. Explain the use of `*args` and `kwargs` in Python function definitions.
- `*args` is used to pass a variable number of positional arguments to a function, while
`kwargs` is used to pass a variable number of keyword arguments to a function.

15. What is a lambda function in Python? How is it different from a regular function?
- A lambda function is an anonymous function defined using the `lambda` keyword. It
can have any number of parameters but can only have one expression. Lambda functions are
typically used for short, simple operations.

16. Explain the concept of list comprehension in Python.


- List comprehension is a concise way to create lists in Python using a single line of
code. It consists of an expression followed by a for clause, optionally followed by if clauses,
enclosed in square brackets.

17. How do you perform file I/O operations in Python?


- File I/O operations in Python are performed using the `open()` function to open a file,
and methods like `read()`, `write()`, `readline()`, and `close()` to read from and write to the file.

18. What is the purpose of the `with` statement in Python?


- The `with` statement in Python is used to ensure that a resource is properly managed
and released, even if an exception occurs, by automatically closing the resource when the block
of code is exited.

19. How does Python's garbage collection work?


- Python's garbage collection works by automatically deallocating memory for objects
that are no longer referenced or reachable, using reference counting and cyclic garbage
collection.

20. Explain the use of the `map()` and `filter()` functions in Python.
- The `map()` function applies a given function to each item of an iterable and returns a
list of the results. The `filter()` function filters elements of an iterable based on a function that
returns `True` or `False`.

21. What is a generator in Python? How is it different from a regular function?


- A generator in Python is a special type of iterator that generates values on-the-fly using
the `yield` keyword. Generators preserve the state of the function, allowing it to resume
execution from where it left off, unlike regular functions that start execution from the beginning
every time they are called.

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


- To create a virtual environment in Python, you can use the `venv` module by running
`python3 -m venv <name_of_environment>` in the terminal. This creates a directory containing
a Python interpreter and a copy of the standard library specific to the Python version used.

23. What are the different data types available in Python?


- Common data types in Python include integers, floats, strings, lists, tuples, dictionaries,
sets, and booleans.

24. Explain the difference between shallow copy and deep copy in Python.
- Shallow copy creates a new object and inserts references to the original elements into
it, while deep copy creates a new object and recursively inserts copies of the original elements
into it, creating a completely independent copy.

25. What is the purpose of the `__name__` variable in Python?


- The `__name__` variable in Python is a special variable that stores the name of the
current module. When a Python script is executed, `__name__` is set to `"__main__"` if the
script is being run directly; otherwise, it is set to the module's name.

26. How do you handle multithreading in Python?


- Multithreading in Python can be achieved using the `threading` module, which provides
classes and functions for creating and managing threads. However, due to the Global
Interpreter Lock (GIL), multithreading in Python may not provide significant performance
improvements for CPU-bound tasks.
27. Explain the purpose of the `__slots__` attribute in Python classes.
- The `__slots__` attribute in Python classes is used to explicitly declare the attributes
that a class can have. This can help reduce memory usage and improve performance by
preventing the creation of `__dict__` for each instance.

28. What is the difference between a module and a package in Python?


- A module is a single Python file containing Python code, while a package is a directory
containing multiple modules and an `__init__.py` file. Packages are used to organize and
distribute modules.

29. How do you install external packages in Python?


- External packages in Python can be installed using package managers like `pip`. For
example, `pip install package_name`.

30. Explain the use of the `super()` function in Python.


- The `super()` function in Python is used to call methods of a superclass from a
subclass. It is commonly used to access and invoke methods overridden in a subclass.

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


- The `enumerate()` function in Python is used to iterate over a sequence (such as a list)
while keeping track of the index of each item. It returns an enumerate object that yields pairs of
index and value.

32. How do you perform unit testing in Python?


- Unit testing in Python can be done using the `unittest` module, which provides a
framework for organizing and running test cases. Test cases are defined by subclassing
`unittest.TestCase` and writing methods that begin with the prefix `test_`.

33. Explain the purpose of the `asyncio` module in Python.


- The `asyncio` module in Python provides infrastructure for writing single-threaded
concurrent code using coroutines, which are special functions that can suspend and resume
execution asynchronously.

34. What is the purpose of the `__call__()` method in Python?


- The `__call__()` method in Python allows instances of a class to be called as if they
were functions. It is invoked when the instance is called with parentheses.

35. How do you handle JSON data in Python?


- JSON data in Python can be handled using the `json` module, which provides functions
for encoding Python objects into JSON strings (`json.dumps()`) and decoding JSON strings into
Python objects (`json.loads()`).

36. Explain the use of the `os` module in Python.


- The `os` module in Python provides functions for interacting with the operating system,
such as working with files and directories, accessing environment variables, and executing
system commands.

37. What are the different ways to import modules in Python?


- Modules can be imported in Python using the `import` statement, `from ... import ...`
statement, or `importlib` module for dynamic imports. Aliases can also be used with the `as`
keyword.

38. How do you create a dictionary in Python?


- Dictionaries in Python are created using curly braces `{ }` and contain key-value pairs
separated by colons `:`. For example, `my_dict = {'key1': 'value1', 'key2': 'value2'}`.

39. Explain the purpose of the `re` module in Python.


- The `re` module in Python provides support for regular expressions, allowing you to
search, match, and manipulate text using patterns.

40. What is the purpose of the `itertools` module in Python?


- The `itertools` module in Python provides functions for creating iterators for efficient
looping and combining elements from iterables.

41. How do you sort a list in Python?


- Lists in Python can be sorted using the `sorted()` function, which returns a new sorted
list without modifying the original list, or by using the `sort()` method, which sorts the list in
place.

42. Explain the purpose of the `logging` module in Python.


- The `logging` module in Python provides a flexible framework for emitting log
messages from Python programs. It supports different levels of logging, customizable
formatting, and multiple handlers for directing log messages to various destinations.

43. What is the purpose of the `__dict__` attribute in Python?


- The `__dict__` attribute in Python is a dictionary containing the namespace of a class
or instance. It stores the attributes and methods of the object as key-value pairs.

44. How do you work with regular expressions in Python?


- Regular expressions in Python are supported through the `re` module, which provides
functions like `re.search()`, `re.match()`, and `re.findall()` for searching, matching, and extracting
text using regular expressions.

45. Explain the purpose of the `functools` module in Python.


- The `functools` module in Python provides higher-order functions and operations for
working with functions, such as `functools.partial()` for creating partial functions,
`functools.reduce()` for reducing sequences, and `functools.wraps()` for creating well-behaved
decorators.

46. What is the purpose of the `__getattr__()` method in Python?


- The `__getattr__()` method in Python is called when an attribute is accessed that does
not exist. It allows custom behavior to be defined for attribute access.

47. How do you handle command line arguments in Python scripts?


- Command line arguments in Python scripts can be handled using the `sys.argv` list, the
`argparse` module for parsing command line arguments, or the `click` library for creating
command line interfaces.

48. Explain the purpose of the `os.path` module in Python.


- The `os.path` module in Python provides functions for common operations on file
paths, such as joining paths, splitting paths, checking file existence, and manipulating file
extensions.

49. What is the purpose of the `contextlib` module in Python?


- The `contextlib` module in Python provides utilities for working with context managers,
including the `contextmanager` decorator for creating context managers and the `closing()`
function for closing resources.

50. How do you serialize and deserialize Python objects?


- Python objects can be serialized into a byte stream using the `pickle` module or
converted to JSON format using the `json` module. Deserialization is the reverse process.

51. What is the purpose of the `pickle` module in Python?


- The `pickle` module in Python is used for serializing and deserializing Python objects
into a byte stream. It can serialize almost any Python object, including custom classes, and is
commonly used for persistence and inter-process communication.

52. How do you handle date and time in Python?


- Date and time in Python can be handled using the `datetime` module, which provides
classes for representing dates, times, and time intervals, as well as functions for formatting and
manipulating dates and times.

53. Explain the purpose of the `collections` module in Python.


- The `collections` module in Python provides additional data structures beyond the built-
in ones, such as `Counter`, `defaultdict`, `deque`, and `namedtuple`, for specialized use cases.

54. What is the purpose of the `heapq` module in Python?


- The `heapq` module in Python provides functions for implementing heaps, a
specialized tree-based data structure used for priority queue operations like insertion, deletion,
and finding the minimum or maximum element.
55. How do you work with sets in Python?
- Sets in Python are unordered collections of unique elements. Sets can be created
using curly braces `{ }` or the `set()` constructor, and support operations like union, intersection,
difference, and symmetric difference.

56. Explain the purpose of the `random` module in Python.


- The `random` module in Python provides functions for generating random numbers,
selecting random elements from sequences, shuffling sequences randomly, and seeding the
random number generator.

57. What is the purpose of the `unittest` module in Python?


- The `unittest` module in Python provides a built-in framework for writing and running
unit tests. It supports test automation, fixture management, and various assertion methods for
verifying expected outcomes.

58. How do you work with iterators and generators in Python?


- Iterators and generators in Python are used for iterating over sequences or generating
values lazily. Iterators are objects that implement the `__iter__()` and `__next__()` methods,
while generators are functions that use the `yield` keyword to generate values.

59. Explain the purpose of the `sys` module in Python.


- The `sys` module in Python provides access to system-specific parameters and
functions, such as command line arguments (`sys.argv`), standard input/output/error streams
(`sys.stdin`, `sys.stdout`, `sys.stderr`), and system exit (`sys.exit()`).

60. What is the purpose of the `warnings` module in Python?


- The `warnings` module in Python provides functions and classes for issuing and
filtering warnings during program execution. It allows developers to control how warnings are
displayed or logged.

61. How do you work with CSV files in Python?


- CSV files in Python can be read and written using the `csv` module, which provides
functions and classes for working with comma-separated values. It supports reading and writing
CSV files in various formats and configurations.

62. Explain the purpose of the `math` module in Python.


- The `math` module in Python provides mathematical functions and constants for
common mathematical operations, such as trigonometric functions, logarithms, exponentiation,
and rounding.

63. What is the purpose of the `statistics` module in Python?


- The `statistics` module in Python provides functions for calculating basic statistical
measures, such as mean, median, mode, variance, and standard deviation, from numerical
data.

64. How do you handle binary data in Python?


- Binary data in Python can be handled using the `bytes` and `bytearray` types for
representing sequences of bytes, as well as the `struct` module for packing and unpacking
binary data into structured formats.

65. Explain the purpose of the `subprocess` module in Python.


- The `subprocess` module in Python provides functions for spawning new processes,
connecting to their input/output/error streams, and communicating with them. It allows Python
programs to interact with external processes and shell commands.

66. What is the purpose of the `multiprocessing` module in Python?


- The `multiprocessing` module in Python provides support for parallel execution using
multiple processes, allowing Python programs to take advantage of multiple CPU cores for
improved performance.

67. How do you work with XML files in Python?


- XML files in Python can be parsed and manipulated using the `xml` module, which
provides functions and classes for reading, writing, and processing XML documents. The
`ElementTree` module is commonly used for working with XML trees.

68. Explain the purpose of the `html` module in Python.


- The `html` module in Python provides functions for escaping and unescaping HTML
entities, as well as functions for parsing and generating HTML documents.

69. What is the purpose of the `socket` module in Python?


- The `socket` module in Python provides low-level networking interfaces for creating
and interacting with network sockets, allowing Python programs to implement network protocols
and communicate over networks.

70. How do you work with network programming in Python?


- Network programming in Python can be done using the `socket` module for low-level
socket programming, the `socketserver` module for creating network servers, and higher-level
libraries like `requests` for making HTTP requests or `paramiko` for SSH connections.

Coding Questions:

Certainly! Here are 30 Python interview questions along with code examples:

1. How do you swap the values of two variables without using a temporary variable?
python
a=5
b = 10
a, b = b, a
print("a =", a) # Output: 10
print("b =", b) # Output: 5

2. Write a Python program to check if a number is prime.


python
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num0.5) + 1):
if num % i == 0:
return False
return True

print(is_prime(17)) # Output: True

3. How do you reverse a string in Python?


python
s = "hello"
reversed_string = s[::-1]
print(reversed_string) # Output: "olleh"

4. Write a Python program to find the factorial of a number.


python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

print(factorial(5)) # Output: 120

5. Write a Python program to count the number of vowels in a string.


python
def count_vowels(string):
vowels = "aeiou"
count = 0
for char in string:
if char.lower() in vowels:
count += 1
return count

print(count_vowels("Hello, World!")) # Output: 3

6. How do you check if a string is a palindrome in Python?


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

print(is_palindrome("radar")) # Output: True

7. Write a Python program to find the largest element in a list.


python
def find_largest(lst):
return max(lst)

print(find_largest([3, 8, 1, 6, 9])) # Output: 9

8. Write a Python program to sort a list of elements using the bubble sort algorithm.
python
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]

my_list = [64, 34, 25, 12, 22, 11, 90]


bubble_sort(my_list)
print(my_list) # Output: [11, 12, 22, 25, 34, 64, 90]

9. Write a Python program to find the Fibonacci sequence up to nth term.


python
def fibonacci(n):
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

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


python
def remove_duplicates(lst):
return list(set(lst))

print(remove_duplicates([1, 2, 3, 2, 1, 5, 6, 5])) # Output: [1, 2, 3, 5, 6]

11. Write a Python program to find the second largest element in a list.
python
def second_largest(lst):
unique_elements = set(lst)
unique_elements.remove(max(unique_elements))
return max(unique_elements)

print(second_largest([3, 8, 1, 6, 9])) # Output: 8

12. How do you find the intersection of two lists in Python?


python
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))

print(intersection([1, 2, 3, 4, 5], [4, 5, 6, 7, 8])) # Output: [4, 5]

13. Write a Python program to check if a string is an anagram of another string.


python
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())

print(is_anagram("listen", "silent")) # Output: True

14. Write a Python program to find the sum of digits of a number.


python
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))

print(sum_of_digits(12345)) # Output: 15
15. How do you find the square root of a number in Python?
python
import math

num = 16
square_root = math.sqrt(num)
print(square_root) # Output: 4.0

16. Write a Python program to check if a year is a leap year.


python
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

print(is_leap_year(2024)) # Output: True

17. How do you convert a list of characters into a string in Python?


python
char_list = ['H', 'e', 'l', 'l', 'o']
string = ''.join(char_list)
print(string) # Output: "Hello"

18. Write a Python program to generate a random number between a given range.
python
import random

random_number = random.randint(1, 100)


print(random_number) # Output: (random integer between 1 and 100)

19. Write a Python program to count the occurrences of a specific character in a string.
python
def count_occurrences(string, char):
return string.count(char)

print(count_occurrences("hello", "l")) # Output: 2

20. How do you find the maximum occurring character in a string in Python?
python
def max_occurrence(string):
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1
return max(char_count, key=char_count.get)

print(max_occurrence("hello")) # Output: "l"

21. Write a Python program to find the sum of all elements in a list.
python
def sum_of_elements(lst):
return sum(lst)

print(sum_of_elements([1, 2, 3, 4, 5])) # Output: 15

22. How do you find the index of an element in a list in Python?


python
def find_index(lst, element):
return lst.index(element)

print(find_index([10, 20, 30, 40, 50], 30)) # Output: 2

23. Write a Python program to remove all occurrences of a specific element from a list.
python
def remove_all_occurrences(lst, element):
return [x for x in lst if x != element]

print(remove_all_occurrences([1, 2, 3, 4, 2, 5, 2], 2)) # Output: [1, 3, 4, 5]

24. Write a Python program to find the length of the longest consecutive sequence of a given
list.
python
def longest_consecutive_sequence(lst):
longest_sequence = 0
current_sequence = 1
lst.sort()
for i in range(1, len(lst)):
if lst[i] == lst[i - 1] + 1:
current_sequence += 1
else:
longest_sequence = max(longest_sequence, current_sequence)
current_sequence = 1
return max(longest_sequence, current_sequence)

print(longest_consecutive_sequence([100, 4, 200, 1, 3, 2])) # Output: 4

25. How do you find the most common element in a list in Python?
python
from collections import Counter

def most_common_element(lst):
counter = Counter(lst)
return counter.most_common(1)[0][0]

print(most_common_element([1, 2, 3, 2, 2, 3, 4, 3, 3])) # Output: 3

26. Write a Python program to find all numbers which are divisible by a given number in a list.
python
def divisible_numbers(lst, divisor):
return [x for x in lst if x % divisor == 0]

print(divisible_numbers([10, 20, 30, 40, 50], 20)) # Output: [20, 40]

27. Write a Python program to find the missing number in a given list of numbers from 1 to n.
python
def find_missing_number(lst):
n = len(lst) + 1
total_sum = n * (n + 1) // 2
actual_sum = sum(lst)
return total_sum - actual_sum

print(find_missing_number([1, 2, 4, 6, 3, 7, 8])) # Output: 5

28. How do you convert a string to lowercase in Python?


python
s = "Hello World"
lowercase_string = s.lower()
print(lowercase_string) # Output: "hello world"

29. Write a Python program to remove leading zeros from an IP address.


python
def remove_leading_zeros(ip):
return '.'.join(str(int(x)) for x in ip.split('.'))

print(remove_leading_zeros("192.168.001.001")) # Output: "192.168.1.1"

30. Write a Python program to find the first non-repeated character in a string.
python
def first_non_repeated_character(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char
return None

print(first_non_repeated_character("hello")) # Output: "h"

You might also like