200+ Python Interview Questions and Answers

Are you preparing for a Python developer interview? I have listed down 150+ important Python interview questions and answers. I am sure it will help you clear the interview. It covers all the areas of Python programming.

Table of Contents

Python Interview Questions and Answers

Here are the Python developer interview questions and answers. These Python developer interview questions are for freshers and 2-5 years of experience professionals. All these questions are coding-related. So, definitely, this will help.

1. What is Python>

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

2. How is Python interpreted?

Answer: Python code is executed line by line by the Python interpreter, making it an interpreted language. This means that Python does not need to be compiled before execution.

3. What are Python’s key features?

Answer: Python’s key features include:

  • Easy to read and write
  • Interpreted language
  • Dynamically typed
  • Extensive standard library
  • Supports multiple programming paradigms
  • Open-source

4. What is PEP 8?

Answer: PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices on how to write Python code. It helps maintain the readability and consistency of Python code.

5. What are Python decorators?

Answer: Decorators are a way to modify or extend the behavior of functions or methods without changing their actual code. They are usually defined with the @decorator_name syntax.

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

Answer: Python’s built-in data types include:

7. What are the differences between list, tuple, set, and dict in Python?

Answer:

  • List: Ordered, mutable, allows duplicate elements. Defined using square brackets [].
  • Tuple: Ordered, immutable, allows duplicate elements. Defined using parentheses ().
  • Set: Unordered, mutable, does not allow duplicate elements. Defined using curly braces {}.
  • Dictionary: Unordered, mutable, stores key-value pairs, keys must be unique. Defined using curly braces {} with key-value pairs separated by colons.

8. How do you convert a list to a set in Python?

Answer: You can convert a Python list to a set using the set() function. This removes duplicate elements from the list.

my_list = [1, 2, 2, 3, 4]
my_set = set(my_list)
print(my_set)  # Output: {1, 2, 3, 4}

9. What is the difference between str and repr in Python?

Answer: The str function is meant to return a human-readable representation of an object, while repr is meant to return an “official” string representation that can ideally be used to recreate the object.

import datetime
now = datetime.datetime.now()
print(str(now))   # Output: '2024-06-01 12:34:56.789012'
print(repr(now))  # Output: 'datetime.datetime(2024, 6, 1, 12, 34, 56, 789012)'

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

Answer: You can check the data type of a variable using the type() function in Python.

x = 10
print(type(x))  # Output: <class 'int'>

11. Explain the concept of mutability in Python with examples.

Answer: Mutability refers to the ability of an object to change its state or contents after it is created.

  • Mutable objects: Lists, dictionaries, sets.
my_list = [1, 2, 3]
my_list[0] = 4  # List is mutable
print(my_list)  # Output: [4, 2, 3]
  • Immutable objects: Strings, tuples
my_tuple = (1, 2, 3)
# my_tuple[0] = 4  # This will raise a TypeError as tuples are immutable

12. What are frozensets in Python?

Answer: Frozensets are immutable sets. They are like sets but cannot be changed once created. They are defined using the frozenset() function.

my_set = frozenset([1, 2, 3])
# my_set.add(4)  # This will raise an AttributeError as frozensets are immutable

13. Explain the use of namedtuple in Python.

Answer: namedtuple is a factory function for creating tuple subclasses with named fields, making the code more readable and self-documenting.

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

14. How do you create a string in Python?

Answer: You can create a string in Python by enclosing characters in single quotes ('), double quotes ("), triple single quotes ('''), or triple double quotes (""").

str1 = 'Hello'
str2 = "World"
str3 = '''This is a 
multi-line string'''
str4 = """Another 
multi-line string"""

15. How can you concatenate two strings in Python?

Answer: You can concatenate two strings using the + operator or the join() method in Python programming.

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # Output: Hello World

result = " ".join([str1, str2])
print(result)  # Output: Hello World

16. How do you find the length of a string in Python?

Answer: You can find the length of a string using the len() function in Python.

str1 = "Hello World"
print(len(str1))  # Output: 11

17. How do you access individual characters in a string?

Answer: You can access individual characters in a string using indexing. Python uses zero-based indexing.

str1 = "Hello"
print(str1[0])  # Output: H
print(str1[-1])  # Output: o

18. How do you slice a string in Python?

Answer: In Python programming, you can slice a string using the slice notation [start:stop:step].

str1 = "Hello World"
print(str1[0:5])  # Output: Hello
print(str1[6:])  # Output: World
print(str1[::2])  # Output: HloWrd

19. How do you reverse a string in Python?

Answer: You can reverse a string using slicing in Python. Here is a complete code and output.

str1 = "Hello World"
reversed_str = str1[::-1]
print(reversed_str)  # Output: dlroW olleH

20. How do you convert a Python string to uppercase or lowercase?

Answer: You can convert a string to uppercase using the upper() method and to lowercase using the lower() method in Python.

str1 = "Hello World"
print(str1.upper())  # Output: HELLO WORLD
print(str1.lower())  # Output: hello world

21. How do you check if a string contains only digits in Python?

Answer: You can check if a string contains only digits in Python using the isdigit() method.

str1 = "12345"
str2 = "123abc"
print(str1.isdigit())  # Output: True
print(str2.isdigit())  # Output: False

22. How do you replace a substring within a string in Python?

Answer: You can replace a substring within a string using the replace() method in Python.

str1 = "Hello World"
new_str = str1.replace("World", "Python")
print(new_str)  # Output: Hello Python

23. How do you split a string into a list of substrings?

Answer: You can split a string into a list of substrings using the split() method in Python. You can follow the below example.

str1 = "Hello World"
split_list = str1.split()
print(split_list)  # Output: ['Hello', 'World']

str2 = "one,two,three"
split_list2 = str2.split(',')
print(split_list2)  # Output: ['one', 'two', 'three']

24. How do you create a list in Python?

Answer: You can create a list in Python by enclosing elements in square brackets [], separated by commas.

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

25. How do you access elements in a Python list?

Answer: You can access elements in a list using indexing. Python uses zero-based indexing.

Check the example below:

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

26. How do you add elements to a list in Python?

Answer: You can add elements to a list using the append() method to add a single element, or the extend() method to add multiple elements.

Below you can see the complete code.

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

my_list.extend([5, 6])
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]

27. How do you remove elements from a list?

Answer: You can remove elements from a list using the Python remove() method, the pop() method, or the del statement.

Here is a complete example.

my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)  # Output: [1, 2, 4, 5]

popped_element = my_list.pop(1)
print(popped_element)  # Output: 2
print(my_list)  # Output: [1, 4, 5]

del my_list[0]
print(my_list)  # Output: [4, 5]

28. How do you sort a list in Python?

Answer: You can sort a list in Python using the sort() method for in-place sorting or the sorted() function for returning a new sorted list in Python.

my_list = [3, 1, 4, 5, 2]
my_list.sort()
print(my_list)  # Output: [1, 2, 3, 4, 5]

my_list = [3, 1, 4, 5, 2]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 2, 3, 4, 5]

29. How do you reverse a list in Python?

Answer: You can reverse a list using the reverse() method for in-place reversal or the slicing technique.

Below is a complete Python example with code.

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)  # Output: [5, 4, 3, 2, 1]

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)  # Output: [5, 4, 3, 2, 1]

30. How do you check if an element exists in a Python list?

Answer: You can check if an element exists in a list using the in keyword in Python.

Follow the example below.

my_list = [1, 2, 3, 4, 5]
print(3 in my_list)  # Output: True
print(6 in my_list)  # Output: False

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

Answer: You can find the index of an element in a list using the index() method in Python.

my_list = [1, 2, 3, 4, 5]
print(my_list.index(3))  # Output: 2

32. How do you count the occurrences of an element in a Python list?

Answer: You can count the occurrences of an element in a Python list using the count() method.

my_list = [1, 2, 2, 3, 4, 2, 5]
print(my_list.count(2))  # Output: 3

33. How do you copy a list in Python?

Answer: You can copy a list using the copy() method, the slicing technique, or the list() constructor in Python.

You can follow the below code.

my_list = [1, 2, 3, 4, 5]
copy_list = my_list.copy()
print(copy_list)  # Output: [1, 2, 3, 4, 5]

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

copy_list = list(my_list)
print(copy_list)  # Output: [1, 2, 3, 4, 5]

34. What is a dictionary in Python?

Answer: A dictionary in Python is an unordered collection of items. Each item is a key-value pair, where keys are unique and immutable, and values can be of any data type.

35. How do you create a dictionary in Python?

Answer: You can create a dictionary by enclosing key-value pairs in curly braces {}.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

36. How do you access values in a Python dictionary?

Answer: You can access values in a dictionary using the keys in Python.

Below is the complete code:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict['name'])  # Output: John

37. How do you add or update an item in a dictionary?

Answer: You can add or update an item in a dictionary by assigning a value to a key in Python.

my_dict = {'name': 'John', 'age': 30}
my_dict['city'] = 'New York'  # Adding a new key-value pair
my_dict['age'] = 31  # Updating an existing key-value pair
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

38. How do you remove an item from a Python dictionary?

Answer: You can remove an item from a dictionary using the Python pop() method, the del statement, or the popitem() method.

Below is the complete code, that you can run directly.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict.pop('age')
print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}

del my_dict['city']
print(my_dict)  # Output: {'name': 'John'}

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict.popitem()  # Removes the last inserted key-value pair
print(my_dict)  # Output: {'name': 'John', 'age': 30}

39. How do you check if a key exists in a dictionary in Python?

Answer: You can check if a key exists in a dictionary using the in keyword.

my_dict = {'name': 'John', 'age': 30}
print('name' in my_dict)  # Output: True
print('city' in my_dict)  # Output: False

40. How do you iterate over keys and values in a Python dictionary?

Answer: You can iterate over keys and values in a Python dictionary using a for loop.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
    print(f'{key}: {value}')
# Output:
# name: John
# age: 30
# city: New York

41. How do you merge two dictionaries in Python?

Answer: You can merge two dictionaries using the update() method or the ** unpacking operator in Python.

Below is the complete code, and you can see the output below:

dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York', 'age': 31}
dict1.update(dict2)
print(dict1)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York', 'age': 31}
merged_dict = {**dict1, **dict2}
print(merged_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

42. How do you get all keys or values from a Python dictionary?

Answer: You can get all keys using the keys() method and all values using the values() method.

Below is the complete Python code:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
keys = my_dict.keys()
values = my_dict.values()
print(keys)  # Output: dict_keys(['name', 'age', 'city'])
print(values)  # Output: dict_values(['John', 30, 'New York'])

43. How do you create a dictionary with default values?

Answer: You can create a Python dictionary with default values using the defaultdict from the collections module.

Here is the complete code.

from collections import defaultdict
d = defaultdict(int)
d['key1'] += 1
print(d)  # Output: defaultdict(<class 'int'>, {'key1': 1})

44. How do you create a dictionary from two lists?

Answer: You can create a dictionary from two lists using the zip() function in Python.

Here is the code you can follow.

keys = ['name', 'age', 'city']
values = ['John', 30, 'New York']
my_dict = dict(zip(keys, values))
print(my_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

45. How do you sort a dictionary by keys or values?

Answer: You can sort a dictionary by keys or values using the sorted() function in Python.

Below is the complete Python code, this code directly you can run and it will provide the output.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
sorted_by_keys = dict(sorted(my_dict.items()))
print(sorted_by_keys)  # Output: {'age': 30, 'city': 'New York', 'name': 'John'}

sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_by_values)  # Output: {'age': 30, 'city': 'New York', 'name': 'John'}

46. How do you use dictionary comprehension in Python?

Answer: Dictionary comprehension is a concise way to create dictionaries. It follows the format {key: value for item in iterable}.

squares = {x: x**2 for x in range(6)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

47. How do you remove all items from a dictionary?

Answer: You can remove all items from a dictionary using the clear() method in Python.

Below is an example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict.clear()
print(my_dict)  # Output: {}

48. How do you copy a dictionary in Python?

Answer: You can copy a dictionary using the copy() method or the dict() constructor in Python.

You can follow the below code.

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
copy_dict = original_dict.copy()
print(copy_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

copy_dict = dict(original_dict)
print(copy_dict)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

49. How do you get a value from a dictionary with a default value if the key does not exist?

Answer: You can use the get() method to retrieve a value from a dictionary and provide a default value if the key does not exist.

my_dict = {'name': 'John', 'age': 30}
print(my_dict.get('name', 'Unknown'))  # Output: John
print(my_dict.get('city', 'Unknown'))  # Output: Unknown

50. How do you update multiple keys and values in a dictionary in Python?

Answer: You can update multiple keys and values in a dictionary using the update() method.

Below is the complete code.

my_dict = {'name': 'John', 'age': 30}
updates = {'city': 'New York', 'age': 31}
my_dict.update(updates)
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

51. What is the difference between dict.items(), dict.keys(), and dict.values()?

Answer:

  • dict.items(): Returns a view object that displays a list of a dictionary’s key-value tuple pairs.
  • dict.keys(): Returns a view object that displays a list of all the keys in the dictionary.
  • dict.values(): Returns a view object that displays a list of all the values in the dictionary.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict.items())  # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
print(my_dict.keys())  # Output: dict_keys(['name', 'age', 'city'])
print(my_dict.values())  # Output: dict_values(['John', 30, 'New York'])

52. How do you create a dictionary with keys from a list and values set to a default value?

Answer: You can create a dictionary with keys from a list and values set to a default value using the fromkeys() method.

keys = ['name', 'age', 'city']
default_value = 'Unknown'
my_dict = dict.fromkeys(keys, default_value)
print(my_dict)  # Output: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}

53. How do you iterate over only the keys or only the values in a Python dictionary?

Answer: You can iterate over only the keys using dict.keys() and only the values using dict.values() in Python.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict.keys():
    print(key)
# Output:
# name
# age
# city

for value in my_dict.values():
    print(value)
# Output:
# John
# 30
# New York

54. How do you create a nested dictionary?

Answer: A nested dictionary is a dictionary within a dictionary. You can create it by assigning a dictionary as a value to a key. This is a Python developer interview question that almost everyone asks.

nested_dict = {
    'person1': {'name': 'John', 'age': 30},
    'person2': {'name': 'Jane', 'age': 25}
}
print(nested_dict)
# Output: {'person1': {'name': 'John', 'age': 30}, 'person2': {'name': 'Jane', 'age': 25}

55. How do you flatten a nested dictionary in Python?

Answer: Flattening a nested dictionary involves converting it into a single-level dictionary. This can be done using a custom function.

You can follow the below code:

def flatten_dict(d, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

nested_dict = {'person': {'name': 'John', 'age': 30}}
flat_dict = flatten_dict(nested_dict)
print(flat_dict)  # Output: {'person_name': 'John', 'person_age': 30}

56. How do you remove and return an arbitrary key-value pair from a dictionary?

Answer: You can remove and return an arbitrary key-value pair from a dictionary using the popitem() method in Python.

Below is the sample code.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
removed_item = my_dict.popitem()
print(removed_item)  # Output: ('city', 'New York')
print(my_dict)  # Output: {'name': 'John', 'age': 30}

57. How do you create a dictionary using dictionary comprehension in Python?

Answer: You can create a dictionary using dictionary comprehension in Python, which is a concise way to create dictionaries.

squares = {x: x**2 for x in range(6)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

58. How do you handle missing keys in a Python dictionary?

Answer: You can handle missing keys in a dictionary using the get() method with a default value, or by using defaultdict from the collections module.

This is another important Python developer question you will get it.

Below is the complete answer.

my_dict = {'name': 'John', 'age': 30}
print(my_dict.get('city', 'Unknown'))  # Output: Unknown

from collections import defaultdict
d = defaultdict(lambda: 'Unknown')
d['name'] = 'John'
print(d['city'])  # Output: Unknown

59. How do you combine two dictionaries while summing the values of common keys in Python?

Answer: You can combine two dictionaries while summing the values of common keys using a dictionary comprehension.

from collections import Counter
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 2, 'b': 3, 'd': 4}
combined_dict = dict(Counter(dict1) + Counter(dict2))
print(combined_dict)  # Output: {'a': 3, 'b': 5, 'c': 3, 'd': 4}

60. How do you get the maximum and minimum values in a Python dictionary?

Answer: You can get the maximum and minimum values in a Python dictionary using the max() and min() functions along with the values() method.

Below is the complete code:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
max_value = max(my_dict.values())
min_value = min(my_dict.values())
print(max_value)  # Output: 4
print(min_value)  # Output: 1

61. How do you create a Python dictionary from a list of keys with the same value?

Answer: You can create a dictionary from a list of keys with the same value using dictionary comprehension.

Below is the complete code.

keys = ['a', 'b', 'c']
value = 0
my_dict = {key: value for key in keys}
print(my_dict)  # Output: {'a': 0, 'b': 0, 'c': 0}

62. How do you find the key associated with the maximum value in a Python dictionary?

Answer: You can find the key associated with the maximum value in a Python dictionary using the max() function with the key argument.

Below is the complete code.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
max_key = max(my_dict, key=my_dict.get)
print(max_key)  # Output: 'd'

63. How do you find the key associated with the minimum value in a Python dictionary?

Answer: You can find the key associated with the minimum value in a dictionary using the min() function with the key argument.

Follow the below code.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
min_key = min(my_dict, key=my_dict.get)
print(min_key)  # Output: 'a'

64. How do you safely remove a key from a Python dictionary if it might not exist?

Answer: You can safely remove a key from a dictionary using the pop() method with a default value in Python.

Here is the complete code.

my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('d', None)
print(removed_value)  # Output: None
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

65. How do you convert a dictionary into a list of tuples?

Answer: You can convert a dictionary into a list of tuples using the items() method in Python.

Here is the complete code.

my_dict = {'a': 1, 'b': 2, 'c': 3}
list_of_tuples = list(my_dict.items())
print(list_of_tuples)  # Output: [('a', 1), ('b', 2), ('c', 3)]

66. How do you convert a list of tuples into a dictionary?

Answer: You can convert a list of tuples into a dictionary using the dict() constructor in Python.

Here is the complete code.

list_of_tuples = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(list_of_tuples)
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

67. How do you create a dictionary with keys as strings and values as lists in Python?

Answer: You can create a dictionary with keys as strings and values as lists using dictionary comprehension in Python.

You can follow the below code.

keys = ['a', 'b', 'c']
my_dict = {key: [] for key in keys}
print(my_dict)  # Output: {'a': [], 'b': [], 'c': []}

68. How do you group values in a dictionary based on keys?

Answer: You can group values in a dictionary based on keys using the defaultdict from the collections module.

from collections import defaultdict

data = [('a', 1), ('b', 2), ('a', 3), ('b', 4), ('c', 5)]
grouped_dict = defaultdict(list)
for key, value in data:
    grouped_dict[key].append(value)

print(grouped_dict)
# Output: defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2, 4], 'c': [5]})

69. How do you create a dictionary with keys from a list and values generated by a function?

Answer: You can create a dictionary with keys from a list and values generated by a function using dictionary comprehension.

keys = ['a', 'b', 'c']
my_dict = {key: len(key) for key in keys}
print(my_dict)  # Output: {'a': 1, 'b': 1, 'c': 1}

70. How do you filter a Python dictionary based on its values?

Answer: You can filter a dictionary based on its values using dictionary comprehension.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in my_dict.items() if v > 2}
print(filtered_dict)  # Output: {'c': 3, 'd': 4}

71. How do you filter a dictionary based on its keys?

Answer: You can filter a dictionary based on its keys using dictionary comprehension in Python.

Here is the complete code.

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in my_dict.items() if k in ['a', 'd']}
print(filtered_dict)  # Output: {'a': 1, 'd': 4}

72. How do you swap keys and values in a Python dictionary?

Answer: You can swap keys and values in a dictionary using dictionary comprehension.

Below is the complete Python code.

my_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {v: k for k, v in my_dict.items()}
print(swapped_dict)  # Output: {1: 'a', 2: 'b', 3: 'c'}

73. How do you increment the value of a key in a Python dictionary?

Answer: You can increment the value of a key in a dictionary by accessing the key and using the += operator. If the key might not exist, you can use the defaultdict from the collections module or the setdefault() method.

my_dict = {'a': 1, 'b': 2}
my_dict['a'] += 1
print(my_dict)  # Output: {'a': 2, 'b': 2}

from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d)  # Output: defaultdict(<class 'int'>, {'a': 1})

my_dict = {}
my_dict['a'] = my_dict.setdefault('a', 0) + 1
print(my_dict)  # Output: {'a': 1}

74. How do you initialize a dictionary with default values in Python?

Answer: You can initialize a dictionary with default values using the defaultdict from the collections module.

Here is the complete code.

from collections import defaultdict
d = defaultdict(lambda: 'default_value')
print(d['a'])  # Output: default_value

75. How do you remove duplicate values from a Python dictionary?

Answer: You can remove duplicate values from a dictionary by creating a new dictionary that only includes unique values in Python.

Here is the complete code:

my_dict = {'a': 1, 'b': 2, 'c': 2, 'd': 3}
unique_values = {}
for key, value in my_dict.items():
    if value not in unique_values.values():
        unique_values[key] = value
print(unique_values)  # Output: {'a': 1, 'b': 2, 'd': 3}

76. How do you convert a dictionary to a JSON string?

Answer: You can convert a dictionary to a JSON string using the json.dumps() method from the json module in Python.

Here is the complete code.

import json
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
json_str = json.dumps(my_dict)
print(json_str)  # Output: {"name": "John", "age": 30, "city": "New York"}

77. What is a tuple in Python?

Answer: A tuple in Python is an immutable, ordered collection of elements. Tuples are defined by enclosing the elements in parentheses () and separated by commas.

my_tuple = (1, 2, 3)

78. How do you create a tuple with a single element?

Answer: To create a tuple with a single element, you need to include a trailing comma after the element.

single_element_tuple = (1,)
print(type(single_element_tuple))  # Output: <class 'tuple'>

79. How can you access elements in a tuple in Python?

Answer: You can access elements in a tuple using indexing, similar to lists in Python.

Here is the complete code.

my_tuple = (1, 2, 3)
print(my_tuple[0])  # Output: 1
print(my_tuple[1])  # Output: 2
print(my_tuple[-1])  # Output: 3

80. How do you concatenate two tuples in Python?

Answer: You can concatenate two tuples using the + operator in Python.

Below is an example.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)  # Output: (1, 2, 3, 4, 5, 6)

81. How do you repeat elements in a tuple?

Answer: You can repeat elements in a tuple using the * operator in Python.

my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 2
print(repeated_tuple)  # Output: (1, 2, 3, 1, 2, 3)

82. How do you unpack elements of a tuple in Python?

Answer: You can unpack elements of a tuple by assigning them to variables.

my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 3

83. How can you check if an element exists in a tuple?

Answer: You can check if an element exists in a tuple using the in keyword. Here is an example:

my_tuple = (1, 2, 3)
print(2 in my_tuple)  # Output: True
print(4 in my_tuple)  # Output: False

84. How do you get the length of a tuple in Python?

Answer: In Python, you can get the length of a tuple using the len() function.

my_tuple = (1, 2, 3)
print(len(my_tuple))  # Output: 3

85. How do you convert a list to a tuple in Python?

Answer: You can convert a list to a tuple using the tuple() constructor. You can follow the below example:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # Output: (1, 2, 3)

86. How do you convert a tuple to a list?

Answer: You can convert a tuple to a list using the list() constructor in Python.

my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)  # Output: [1, 2, 3]

87. What is an array in Python?

Answer: An array is a data structure that can hold multiple values of the same data type. Unlike lists, arrays in Python require that all elements be of the same type. Arrays are provided by the array module.

88. How do you create an array in Python?

Answer: You can create an array using the array module in Python. Below is the complete code to create a Python array.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
print(my_array)  # Output: array('i', [1, 2, 3, 4])

89. How do you access elements in an array in Python?

Answer: You can access elements in an array using indexing in Python.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
print(my_array[0])  # Output: 1
print(my_array[2])  # Output: 3

90. How do you append an element to an array?

Answer: You can append an element to an array using the append() method.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_array.append(5)
print(my_array)  # Output: array('i', [1, 2, 3, 4, 5])

91. How do you extend an array with another array in Python?

Answer: You can extend an array with another array using the extend() method.

Here is the example.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_array.extend([5, 6, 7])
print(my_array)  # Output: array('i', [1, 2, 3, 4, 5, 6, 7])
Python Interview Questions and Answers

92. How do you insert an element at a specific position in an array in Python?

Answer: You can insert an element at a specific position in an array using the insert() method.

You can follow the code below.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_array.insert(2, 5)
print(my_array)  # Output: array('i', [1, 2, 5, 3, 4])

93. How do you remove an element from an array in Python?

Answer: You can remove an element from an array using the remove() method.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_array.remove(3)
print(my_array)  # Output: array('i', [1, 2, 4])

94. How do you pop an element from a Python array?

Answer: You can pop an element from an array using the pop() method. This method removes and returns the element at the specified position.

Here is the complete code:

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
popped_element = my_array.pop(1)
print(popped_element)  # Output: 2
print(my_array)  # Output: array('i', [1, 3, 4])

95. How do you find the index of an element in an array in Python?

Answer: You can find the index of an element in an array using the index() method.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
index_of_element = my_array.index(3)
print(index_of_element)  # Output: 2

96. How do you reverse the elements of an array in Python?

Answer: You can reverse the elements of an array using the reverse() method in Python.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_array.reverse()
print(my_array)  # Output: array('i', [4, 3, 2, 1])

97. How do you get the buffer information of an array?

Answer: You can get the buffer information of an array using the buffer_info() method. This method returns a tuple containing the memory address and the length of the array.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
buffer_info = my_array.buffer_info()
print(buffer_info)  # Output: (address, 4)

98. How do you count the occurrences of an element in an array in Python?

Answer: You can count the occurrences of an element in an array using the count() method.

Here is the complete code.

import array as arr

my_array = arr.array('i', [1, 2, 2, 3, 4])
count_of_element = my_array.count(2)
print(count_of_element)  # Output: 2

99. How do you convert an array to a list in Python?

Answer: You can convert an array to a list using the tolist() method in Python.

Here is the complete program.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
my_list = my_array.tolist()
print(my_list)  # Output: [1, 2, 3, 4]

100. How do you slice an array in Python?

Answer: You can slice an array using the slicing syntax, similar to lists.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4, 5])
sliced_array = my_array[1:4]
print(sliced_array)  # Output: array('i', [2, 3, 4])

101. How do you iterate over the elements of a Python array?

Answer: You can iterate over the elements of an array using a for loop in Python.

import array as arr

my_array = arr.array('i', [1, 2, 3, 4])
for element in my_array:
    print(element)
# Output:
# 1
# 2
# 3
# 4

102. How do you sort the elements of a Python array?

Answer: You can sort the elements of an array using the sorted() function, which returns a new sorted list.

Here is the complete code.

import array as arr

my_array = arr.array('i', [4, 3, 2, 1])
sorted_array = sorted(my_array)
print(sorted_array)  # Output: [1, 2, 3, 4]

103. What is a for loop in Python?

Answer: A for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each element in the sequence.

for i in [1, 2, 3]:
    print(i)
# Output:
# 1
# 2
# 3

104. What is a while loop in Python?

Answer: A while loop in Python repeatedly executes a block of code as long as a given condition is True.

i = 1
while i < 4:
    print(i)
    i += 1
# Output:
# 1
# 2
# 3

105. How do you use the range() function in a for loop?

Answer: The range() function generates a sequence of numbers, which can be used in a for loop to iterate over a specific range in Python. Here is the code.

for i in range(1, 4):
    print(i)
# Output:
# 1
# 2
# 3

106. How do you use a for loop to iterate over a dictionary?

Answer: You can iterate over a dictionary using a for loop to access its keys, values, or key-value pairs.

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
    print(key, my_dict[key])
# Output:
# a 1
# b 2
# c 3

for key, value in my_dict.items():
    print(key, value)
# Output:
# a 1
# b 2
# c 3

107. How do you use a for loop with the enumerate() function in Python?

Answer: The enumerate() function adds a counter to an iterable and returns it as an enumerate object, which can be used in a for loop in Python.

Here is the complete code:

my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
    print(index, value)
# Output:
# 0 a
# 1 b
# 2 c

108. How do you use a for loop with the zip() function?

Answer: The zip() function combines multiple iterables and returns an iterator of tuples, which can be used in a for loop.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for num, char in zip(list1, list2):
    print(num, char)
# Output:
# 1 a
# 2 b
# 3 c

109. How do you use a while loop with a break statement in Python?

Answer: The break statement can be used inside a while loop to exit the loop when a certain condition is met.

Here is the complete code:

i = 1
while i < 10:
    print(i)
    if i == 3:
        break
    i += 1
# Output:
# 1
# 2
# 3

110. How do you use a while loop with a continue statement?

Answer: The continue statement can be used inside a while loop to skip the rest of the code inside the loop for the current iteration and move to the next iteration.

Here is a complete example.

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)
# Output:
# 1
# 2
# 4
# 5

111. How do you use nested for loops in Python?

Answer: Nested for loops are used to iterate over multiple sequences, where one loop is placed inside another.

Below is the complete example.

for i in range(1, 4):
    for j in range(1, 3):
        print(i, j)
# Output:
# 1 1
# 1 2
# 2 1
# 2 2
# 3 1
# 3 2

112. How do you use a for loop with a else clause in Python?

Answer: The else clause in a for loop is executed when the loop completes normally (i.e., not terminated by a break statement).

for i in range(1, 4):
    print(i)
else:
    print("Loop completed")
# Output:
# 1
# 2
# 3
# Loop completed

113. What is an if statement in Python?

Answer: An if statement in Python is used to test a condition. If the condition is True, the block of code inside the if statement is executed.

x = 10
if x > 5:
    print("x is greater than 5")
# Output: x is greater than 5

114. What is an else statement in Python?

Answer: An else statement in Python is used to execute a block of code if the condition in the if statement is False.

Below is an example.

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")
# Output: x is not greater than 5

115. What is an elif statement in Python?

Answer: An elif (short for else if) statement in Python is used to check multiple conditions. If the condition for if is False, it checks the condition of the elif block.

Here is an example.

x = 5
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")
# Output: x is equal to 5

116. How do you use nested if statements in Python?

Answer: You can use nested if statements to check multiple conditions within another if or elif block.

x = 10
if x > 5:
    if x < 15:
        print("x is between 5 and 15")
# Output: x is between 5 and 15

117. How do you use the and operator in an if statement in Python?

Answer: The and operator is used to combine multiple conditions in an if statement. The block of code is executed if all conditions are True.

x = 10
if x > 5 and x < 15:
    print("x is between 5 and 15")
# Output: x is between 5 and 15

118. How do you use the or operator in an if statement in Python?

Answer: The or operator is used to combine multiple conditions in an if statement. The block of code is executed if at least one condition is True.

x = 20
if x < 5 or x > 15:
    print("x is not between 5 and 15")
# Output: x is not between 5 and 15

119. How do you use the not operator in an if statement in Python?

Answer: The not operator is used to invert the boolean value of a condition in an if statement in Python.

Below is the complete code.

x = 10
if not x < 5:
    print("x is not less than 5")
# Output: x is not less than 5

120. How do you use the ternary (conditional) operator in Python?

Answer: The ternary operator in Python allows you to write a conditional statement in a single line. The syntax is value_if_true if condition else value_if_false.

x = 10
result = "greater than 5" if x > 5 else "not greater than 5"
print(result)  # Output: greater than 5

121. How do you check for multiple conditions using elif?

Answer: You can check for multiple conditions using multiple elif blocks in an if statement in Python.

You can check the below code.

x = 15
if x < 5:
    print("x is less than 5")
elif x < 10:
    print("x is between 5 and 10")
elif x < 20:
    print("x is between 10 and 20")
else:
    print("x is 20 or more")
# Output: x is between 10 and 20

122. How do you use the pass statement in an if block?

Answer: The pass statement is used as a placeholder in an if block when no action is required. It allows the code to run without errors.

x = 10
if x > 5:
    pass  # Do nothing
else:
    print("x is 5 or less")

123. Write a program in Python to calculate simple interest.

Answer: This is the complete Python program for calculating simple interest.

def calculate_simple_interest(principal, rate, time):
    simple_interest = (principal * rate * time) / 100
    return simple_interest

principal = 1000
rate = 5
time = 2
interest = calculate_simple_interest(principal, rate, time)
print(f"Simple Interest: {interest}")
# Output: Simple Interest: 100.0

124. Write a program in Python to check if a number is an Armstrong number.

Answer: This is the Python program to check, if a number is an Armstrong number.

def is_armstrong_number(number):
    num_str = str(number)
    num_len = len(num_str)
    sum_of_powers = sum(int(digit) ** num_len for digit in num_str)
    return sum_of_powers == number

number = 153
if is_armstrong_number(number):
    print(f"{number} is an Armstrong number")
else:
    print(f"{number} is not an Armstrong number")
# Output: 153 is an Armstrong number

125. Write a program in Python to find the factorial of a number.

Answer: Here is the Python program to find the factorial of a number.

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

number = 5
result = factorial(number)
print(f"Factorial of {number} is {result}")
# Output: Factorial of 5 is 120

126. Write a program in Python to generate the Fibonacci sequence up to n terms.

Answer: Below is the Python program to generate the Fibonacci sequence up to n terms.

def fibonacci(n):
    sequence = []
    a, b = 0, 1
    for _ in range(n):
        sequence.append(a)
        a, b = b, a + b
    return sequence

n = 10
fib_sequence = fibonacci(n)
print(f"Fibonacci sequence up to {n} terms: {fib_sequence}")
# Output: Fibonacci sequence up to 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

127. Write a program in Python to check if a string is a palindrome.

Answer: Below is the complete program in Python to check if a string is a palindrome.

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

string = "radar"
if is_palindrome(string):
    print(f"{string} is a palindrome")
else:
    print(f"{string} is not a palindrome")
# Output: radar is a palindrome

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

Answer: Below is the complete code to find the largest element in a list in Python.

def find_largest_element(lst):
    return max(lst)

numbers = [1, 2, 3, 4, 5]
largest = find_largest_element(numbers)
print(f"The largest element in the list is {largest}")
# Output: The largest element in the list is 5

129. Write a program in Python to reverse a string.

Answer: Here is the program in Python to reverse a string.

def reverse_string(s):
    return s[::-1]

string = "hello"
reversed_string = reverse_string(string)
print(f"Reversed string: {reversed_string}")
# Output: Reversed string: olleh

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

Answer: Below is the program in Python to count the number of vowels in a string.

def count_vowels(s):
    vowels = "aeiouAEIOU"
    count = 0
    for char in s:
        if char in vowels:
            count += 1
    return count

string = "hello world"
vowel_count = count_vowels(string)
print(f"Number of vowels in '{string}': {vowel_count}")
# Output: Number of vowels in 'hello world': 3

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

Answer: Below is the complete Python code to find the sum of digits of a number.

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

number = 1234
sum_digits = sum_of_digits(number)
print(f"Sum of digits of {number} is {sum_digits}")
# Output: Sum of digits of 1234 is 10

132. Write a program in Python to check if a number is prime.

Answer: Below is the complete Python program to check if a number in prime or not.

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

number = 29
if is_prime(number):
    print(f"{number} is a prime number")
else:
    print(f"{number} is not a prime number")
# Output: 29 is a prime number

133. How do you open a file in Python?

Answer: You can open a file in Python using the open() function, which returns a file object. You can specify the mode in which to open the file, such as read ('r'), write ('w'), append ('a'), and binary modes ('rb''wb', etc.).

file = open('example.txt', 'r')

134. How do you read the content of a file in Python?

Answer: You can read the content of a file using the read() method.

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

135. How do you write to a file in Python?

Answer: You can write to a file using the write() method. If the file does not exist, it will be created.

with open('example.txt', 'w') as file:
    file.write("Hello, world!")

136. How do you append content to an existing file in Python?

Answer: You can append content to an existing file using the append() method.

with open('example.txt', 'a') as file:
    file.write("\nAppending this line.")

137. How do you read a file line by line in Python?

Answer: You can read a file line by line using the readline() method or by iterating over the file object.

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

138. How do you check if a file exists in Python?

Answer: You can check if a file exists using the os.path.exists() method from the os module.

import os

if os.path.exists('example.txt'):
    print("File exists")
else:
    print("File does not exist")

139. How do you delete a file in Python?

Answer: You can delete a file using the os.remove() method from the os module.

import os

if os.path.exists('example.txt'):
    os.remove('example.txt')
    print("File deleted")
else:
    print("File does not exist")

140. How do you rename a file in Python?

Answer: You can rename a file using the os.rename() method from the os module.

import os

os.rename('old_name.txt', 'new_name.txt')

141. How do you get the size of a file in Python?

Answer: You can get the size of a file using the os.path.getsize() method from the os module.

import os

file_size = os.path.getsize('example.txt')
print(f"File size: {file_size} bytes")

142. How do you close a file in Python?

Answer: You can close a file using the close() method. However, it is recommended to use the with statement, which automatically closes the file when the block is exited.

file = open('example.txt', 'r')
content = file.read()
file.close()

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

143. Does Python have a built-in switch-case statement?

Answer: No, Python does not have a built-in switch-case statement like some other programming languages. However, similar functionality can be achieved using dictionaries or the match statement introduced in Python 3.10.

144. How can you implement a switch-case using dictionaries in Python?

Answer: You can use dictionaries to emulate switch-case functionality by mapping keys to functions or values.

def case_one():
    return "Case 1"

def case_two():
    return "Case 2"

def default_case():
    return "Default case"

switch = {
    1: case_one,
    2: case_two
}

def switch_case(case):
    return switch.get(case, default_case)()

print(switch_case(1))  # Output: Case 1
print(switch_case(3))  # Output: Default case

145. How can you use the match statement introduced in Python 3.10 for switch-case functionality?

Answer: The match statement in Python 3.10 provides a way to perform pattern matching, which can be used as an alternative to switch-case.

def match_case(value):
    match value:
        case 1:
            return "Case 1"
        case 2:
            return "Case 2"
        case _:
            return "Default case"

print(match_case(1))  # Output: Case 1
print(match_case(3))  # Output: Default case

146. How do you handle multiple cases with the same outcome using the match statement?

Answer: You can handle multiple cases with the same outcome by separating the cases with a pipe (|).

def match_case(value):
    match value:
        case 1 | 2 | 3:
            return "Case 1, 2, or 3"
        case _:
            return "Default case"

print(match_case(2))  # Output: Case 1, 2, or 3
print(match_case(4))  # Output: Default case

147. How can you use lambdas in a dictionary-based switch-case implementation?

Answer: You can use lambda functions in a dictionary to perform calculations or operations directly.

switch = {
    1: lambda: "Case 1",
    2: lambda: "Case 2",
    3: lambda x: f"Case 3 with value {x}"
}

def switch_case(case, value=None):
    func = switch.get(case, lambda: "Default case")
    return func() if value is None else func(value)

print(switch_case(1))  # Output: Case 1
print(switch_case(3, 10))  # Output: Case 3 with value 10
print(switch_case(4))  # Output: Default case

148. How can you use functions in a dictionary-based switch-case implementation?

Answer: You can map dictionary keys to functions and call them based on the case.

def case_one():
    return "Case 1"

def case_two():
    return "Case 2"

def case_three(value):
    return f"Case 3 with value {value}"

switch = {
    1: case_one,
    2: case_two,
    3: case_three
}

def switch_case(case, value=None):
    func = switch.get(case, lambda: "Default case")
    return func() if value is None else func(value)

print(switch_case(1))  # Output: Case 1
print(switch_case(3, 10))  # Output: Case 3 with value 10
print(switch_case(4))  # Output: Default case

149. How do you handle default cases in a dictionary-based switch-case implementation?

Answer: You can provide a default function or value using the get() method’s default parameter.

switch = {
    1: lambda: "Case 1",
    2: lambda: "Case 2"
}

def switch_case(case):
    return switch.get(case, lambda: "Default case")()

print(switch_case(1))  # Output: Case 1
print(switch_case(3))  # Output: Default case

150. How can you use the match statement to match complex patterns?

Answer: The match statement can match complex patterns, including tuples and lists. Here is the complete code.

def match_case(value):
    match value:
        case (1, x):
            return f"Tuple with 1 and {x}"
        case [1, 2, 3]:
            return "List with 1, 2, 3"
        case _:
            return "Default case"

print(match_case((1, 10)))  # Output: Tuple with 1 and 10
print(match_case([1, 2, 3]))  # Output: List with 1, 2, 3
print(match_case(4))  # Output: Default case

151. How can you use the match statement to match class instances?

Answer: You can use the match statement to match class instances by specifying the class name and attributes.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def match_case(value):
    match value:
        case Point(x, y):
            return f"Point with coordinates ({x}, {y})"
        case _:
            return "Default case"

point = Point(1, 2)
print(match_case(point))  # Output: Point with coordinates (1, 2)
print(match_case(4))  # Output: Default case

152. How can you handle multiple types in a single case using the match statement?

Answer: You can handle multiple types in a single case by using the | operator to combine patterns.

def match_case(value):
    match value:
        case int() | float():
            return "Number"
        case str():
            return "String"
        case _:
            return "Default case"

print(match_case(10))  # Output: Number
print(match_case(10.5))  # Output: Number
print(match_case("hello"))  # Output: String
print(match_case([1, 2, 3]))  # Output: Default case

153. How do you get the current date and time in Python?

Answer: You can get the current date and time using the datetime.now() method from the datetime module.

from datetime import datetime

current_datetime = datetime.now()
print(current_datetime)
# Output: 2024-06-01 12:34:56.789012 (example output)

154. How do you format a date in Python?

Answer: You can format a date using the strftime() method from the datetime module.

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
# Output: 2024-06-01 12:34:56 (example output)

155. How do you parse a string into a datetime object in Python?

Answer: You can parse a string into a datetime object using the strptime() method from the datetime module.

from datetime import datetime

date_string = "2024-06-01 12:34:56"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)
# Output: 2024-06-01 12:34:56

156. How do you get the current date in Python?

Answer: You can get the current date using the date.today() method from the datetime module.

from datetime import date

current_date = date.today()
print(current_date)
# Output: 2024-06-01 (example output)

157. How do you calculate the difference between two dates in Python?

Answer: You can calculate the difference between two dates using the - operator, which returns a timedelta object.

from datetime import date

date1 = date(2024, 6, 1)
date2 = date(2023, 6, 1)
difference = date1 - date2
print(difference.days)
# Output: 366 (example output, considering a leap year)

158. How do you add or subtract days from a date in Python?

Answer: You can add or subtract days from a date using the timedelta object from the datetime module.

from datetime import date, timedelta

current_date = date.today()
new_date = current_date + timedelta(days=10)
print(new_date)
# Output: 2024-06-11 (example output)

159. How do you get the day of the week from a date in Python?

Answer: You can get the day of the week using the weekday() method, which returns an integer (0 for Monday, 6 for Sunday).

from datetime import date

current_date = date.today()
day_of_week = current_date.weekday()
print(day_of_week)
# Output: 5 (example output for Saturday)

160. How do you get the current time in Python?

Answer: You can get the current time using the time() method from the datetime module.

from datetime import datetime

current_time = datetime.now().time()
print(current_time)
# Output: 12:34:56.789012 (example output)

161. How do you create a datetime object for a specific date and time in Python?

Answer: You can create a datetime object for a specific date and time using the datetime() constructor from the datetime module.

from datetime import datetime

specific_datetime = datetime(2024, 6, 1, 12, 34, 56)
print(specific_datetime)
# Output: 2024-06-01 12:34:56

162. How do you convert a timestamp to a datetime object in Python?

Answer: You can convert a timestamp to a datetime object using the fromtimestamp() method from the datetime module.

from datetime import datetime

timestamp = 1719875696
datetime_obj = datetime.fromtimestamp(timestamp)
print(datetime_obj)
# Output: 2024-06-01 12:34:56 (example output)

163. What is a set in Python?

Answer: A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove elements, but they do not allow duplicate values.

my_set = {1, 2, 3, 4, 5}
print(my_set)
# Output: {1, 2, 3, 4, 5}

164. How do you create a set in Python?

Answer: You can create a set in Python using curly braces {} or the set() function.

Here is the complete code.

my_set = {1, 2, 3}
print(my_set)
# Output: {1, 2, 3}

another_set = set([4, 5, 6])
print(another_set)
# Output: {4, 5, 6}

165. How do you add an element to a set in Python?

Answer: You can add an element to a set using the add() method in Python.

Below is an example.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
# Output: {1, 2, 3, 4}

166. How do you remove an element from a set in Python?

Answer: You can remove an element from a set using the remove() method. If the element is not present, it raises a KeyError. Alternatively, you can use the discard() method, which does not raise an error if the element is not found.

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
# Output: {1, 3}

my_set.discard(3)
print(my_set)
# Output: {1}

167. How do you check if an element is in a set in Python?

Answer: You can check if an element is in a set using the in keyword in Python.

Here is the complete code:

my_set = {1, 2, 3}
print(2 in my_set)
# Output: True

print(4 in my_set)
# Output: False

168. How do you perform set union in Python?

Answer: You can perform set union using the union() method or the | operator.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
# Output: {1, 2, 3, 4, 5}

union_set = set1 | set2
print(union_set)
# Output: {1, 2, 3, 4, 5}

169. How do you perform set intersection in Python?

Answer: You can perform set intersection using the intersection() method or the & operator.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set)
# Output: {3}

intersection_set = set1 & set2
print(intersection_set)
# Output: {3}

170. How do you perform set difference in Python?

Answer: You can perform set difference using the difference() method or the - operator. Here is an example.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set)
# Output: {1, 2}

difference_set = set1 - set2
print(difference_set)
# Output: {1, 2}

171. How do you perform set symmetric difference in Python?

Answer: You can perform set symmetric difference using the symmetric_difference() method or the ^ operator.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)
# Output: {1, 2, 4, 5}

symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)
# Output: {1, 2, 4, 5}

172. How do you check if a set is a subset of another set in Python?

Answer: You can check if a set is a subset of another set using the issubset() method or the <= operator.

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2))
# Output: True

print(set1 <= set2)
# Output: True

173. What is exception handling in Python?

Answer: Exception handling in Python is a mechanism to handle runtime errors, allowing a program to continue executing or gracefully terminate. It involves using tryexceptelse, and finally blocks to catch and manage exceptions.

This is a must Python interview question for developers.

174. How do you use the try and except blocks in Python?

Answer: The try block contains code that might raise an exception, while the except block contains code that handles the exception.

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

175. How do you catch multiple exceptions in Python?

Answer: You can catch multiple exceptions by specifying them as a tuple in a single except block or by using multiple except blocks.

try:
    result = 10 / 0
except (ZeroDivisionError, ValueError):
    print("Caught an exception")
# Output: Caught an exception

try:
    result = int("a")
except ValueError:
    print("ValueError caught")
except ZeroDivisionError:
    print("ZeroDivisionError caught")
# Output: ValueError caught

176. What is the purpose of the else block in exception handling?

Answer: The else block is executed if no exceptions are raised in the try block. It is useful for code that should only run if the try block succeeds.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Division successful:", result)
# Output: Division successful: 5.0

177. What is the purpose of the finally block in exception handling?

Answer: The finally block contains code that will always execute, regardless of whether an exception was raised or not. It is typically used for cleanup actions, such as closing files or releasing resources.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will always execute")
# Output: This will always execute

178. How do you raise an exception in Python?

Answer: You can raise an exception using the raise statement.

def check_positive(number):
    if number < 0:
        raise ValueError("Number must be positive")
    return number

try:
    check_positive(-1)
except ValueError as e:
    print(e)
# Output: Number must be positive

179. How do you create a custom exception in Python?

Answer: You can create a custom exception by defining a new class that inherits from the Exception class.

Here is a complete code.

class CustomError(Exception):
    pass

try:
    raise CustomError("This is a custom error")
except CustomError as e:
    print(e)
# Output: This is a custom error

180. How do you handle exceptions with a context manager in Python?

Answer: You can handle exceptions in a context manager by using the with statement and a custom context manager class with __enter__ and __exit__ methods.

class ManagedFile:
    def __enter__(self):
        self.file = open('example.txt', 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
        if exc_type:
            print(f"Exception occurred: {exc_val}")
        return True  # Suppress exception

with ManagedFile() as file:
    file.write("Hello, world!")
    raise ValueError("An error occurred")
# Output: Exception occurred: An error occurred

181. How do you log exceptions in Python?

Answer: You can log exceptions using the logging module by calling logging.exception() within an except block.

import logging

logging.basicConfig(level=logging.ERROR)

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("An error occurred")
# Output: ERROR:root:An error occurred
# Traceback (most recent call last):
#   File "<stdin>", line 4, in <module>
# ZeroDivisionError: division by zero

182. How do you use the assert statement for exception handling in Python?

Answer: The assert statement is used to set a condition that must be true; if the condition is false, an AssertionError is raised.

def divide(a, b):
    assert b != 0, "Denominator cannot be zero"
    return a / b

try:
    divide(10, 0)
except AssertionError as e:
    print(e)
# Output: Denominator cannot be zero

183. What is a lambda function in Python?

Answer: A lambda function is an anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression. Example: lambda x, y: x + y.

184. How does Python handle memory management?

Answer: Python uses an automatic memory management system, which includes a private heap containing all Python objects and data structures. The memory manager and garbage collector handle memory allocation and deallocation.

185. What is Object-Oriented Programming (OOP)?

Answer: Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods). OOP focuses on the creation of reusable code and modular design.

186. What is a generator in Python?

Answer: Generators are a type of iterable, like lists or tuples, but they generate values on the fly using the yield keyword. This makes them memory efficient as they produce items one at a time and only when required.

187. Explain the Global Interpreter Lock (GIL).

Answer: The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously. This can be a limitation for CPU-bound multi-threaded programs.

188. What is the difference between deep copy and shallow copy?

Answer: A shallow copy creates a new object but inserts references to the objects found in the original. A deep copy creates a new object and recursively copies all objects found in the original, meaning it duplicates everything.

189. How do you manage packages in Python?

Answer: Python packages are managed using tools like pip, the package installer for Python. You can install, update, and remove packages using pip commands.

190. What is a context manager in Python?

Answer: Context managers allow you to allocate and release resources precisely when you want to. The most common way to use a context manager is with the with statement. Example:

with open('file.txt', 'r') as file:
    data = file.read()

191. Explain the difference between __str__ and __repr__ methods.

Answer: The __str__ method is used to find the “informal” or nicely printable string representation of an object, while __repr__ is used to find the “official” string representation of an object, which can ideally be used to recreate the object.

192. What is the @staticmethod decorator?

Answer: The @staticmethod decorator is used to define a method that does not operate on an instance of the class (i.e., it has no self parameter). It can be called on the class itself or its instances.

193. How does Python’s garbage collection work?

Answer: Python’s garbage collection is based on reference counting and cyclic garbage collector. When an object’s reference count drops to zero, it is automatically deallocated. The cyclic garbage collector detects and collects cyclic references.

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

Answer: The is operator checks for identity, meaning it returns True if two references point to the same object. The == operator checks for equality, meaning it returns True if the values of two objects are equal.

195. Explain the concept of monkey patching in Python.

Answer: Monkey patching refers to the dynamic modifications of a class or module at runtime. This can be useful for altering the behavior of libraries or frameworks without modifying their source code.

196. What is the difference between str and repr in Python?

Answer: The str function is meant to return a human-readable representation of an object, while repr is meant to return an “official” string representation that can ideally be used to recreate the object.

import datetime
now = datetime.datetime.now()
print(str(now))   # Output: '2024-06-01 12:34:56.789012'
print(repr(now))  # Output: 'datetime.datetime(2024, 6, 1, 12, 34, 56, 789012)'

197. What is the difference between bytes and bytearray in Python?

Answer:

  • bytes: Immutable sequence of bytes. Defined using the bytes() function or a bytes literal.
b = bytes([1, 2, 3]) # b[0] = 4 # This will raise a TypeError as bytes are immutable
  • bytearray: Mutable sequence of bytes. Defined using the bytearray() function.
ba = bytearray([1, 2, 3]) ba[0] = 4 # bytearray is mutable print(ba) # Output: bytearray(b'\x04\x02\x03')

198. What are the four main principles of OOP?

Answer: The four main principles of OOP are:

  1. Encapsulation: Bundling the data (attributes) and methods (functions) that operate on the data into a single unit or class, and restricting access to some of the object’s components.
  2. Abstraction: Hiding the complex implementation details and showing only the necessary features of an object.
  3. Inheritance: A mechanism where a new class inherits properties and behavior (methods) from an existing class.
  4. Polymorphism: The ability to present the same interface for different underlying data types, allowing methods to be used interchangeably.

199. How do you define a class in Python?

Answer: You define a class in Python using the class keyword followed by the class name and a colon. Inside the class, you define attributes and methods.

class MyClass:
    def __init__(self, value):
        self.value = value

    def display_value(self):
        print(self.value)

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

Answer: The __init__ method is a special method in Python classes, also known as the constructor. It is automatically called when a new instance of the class is created and is used to initialize the object’s attributes.

class MyClass:
    def __init__(self, value):
        self.value = value

obj = MyClass(10)
print(obj.value)  # Output: 10

201. How do you create an instance of a class in Python?

Answer: You create an instance of a class by calling the class name followed by parentheses, optionally passing arguments if the class constructor requires them.

class MyClass:
    def __init__(self, value):
        self.value = value

obj = MyClass(10)

202. What is inheritance in Python, and how do you implement it?

Answer: Inheritance is a feature in OOP that allows a new class (child class) to inherit attributes and methods from an existing class (parent class). You implement inheritance by passing the parent class as an argument to the child class.

class ParentClass:
    def __init__(self, value):
        self.value = value

    def display_value(self):
        print(self.value)

class ChildClass(ParentClass):
    def __init__(self, value, extra_value):
        super().__init__(value)
        self.extra_value = extra_value

    def display_extra_value(self):
        print(self.extra_value)

child = ChildClass(10, 20)
child.display_value()  # Output: 10
child.display_extra_value()  # Output: 20

203. What is polymorphism in Python, and how is it implemented?

Answer: Polymorphism allows methods to be used interchangeably, even if they belong to different classes. This is often implemented using method overriding or method overloading.

class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Woof"

class Cat(Animal):
    def sound(self):
        return "Meow"

def make_sound(animal):
    print(animal.sound())

dog = Dog()
cat = Cat()
make_sound(dog)  # Output: Woof
make_sound(cat)  # Output: Meow

204. What is encapsulation, and how is it achieved in Python?

Answer: Encapsulation is the bundling of data and methods that operate on the data into a single unit, or class, and restricting access to some of the object’s components. It is achieved using access modifiers like private (__) and protected (_) attributes.

class MyClass:
    def __init__(self, value):
        self.__value = value  # Private attribute

    def get_value(self):
        return self.__value

obj = MyClass(10)
print(obj.get_value())  # Output: 10
# print(obj.__value)  # AttributeError: 'MyClass' object has no attribute '__value'

205. What is method overriding in Python?

Answer: Method overriding allows a child class to provide a specific implementation of a method that is already defined in its parent class. The method in the child class should have the same name and parameters as the method in the parent class.

class ParentClass:
    def display(self):
        print("Parent class display")

class ChildClass(ParentClass):
    def display(self):
        print("Child class display")

child = ChildClass()
child.display()  # Output: Child class display

206. What is a class method and a static method in Python, and how do they differ?

Answer: A class method is a method that is bound to the class and not the instance of the class. It can modify class state that applies across all instances of the class. A static method is a method that does not modify class or instance state and is bound to the class, not the instance.

class MyClass:
    class_variable = 0

    def __init__(self, value):
        self.value = value

    @classmethod
    def class_method(cls):
        cls.class_variable += 1
        return cls.class_variable

    @staticmethod
    def static_method():
        return "This is a static method"

# Using class method
print(MyClass.class_method())  # Output: 1
print(MyClass.class_method())  # Output: 2

# Using static method
print(MyClass.static_method())  # Output: This is a static method

Conclusion

Mastering Python interview questions and answers is crucial for anyone aspiring to become a proficient Python developer. Whether you are a fresher or an experienced professional, you should understand key concepts such as data types, date and time manipulation, set operations, exception handling, and Object-Oriented Programming (OOP) principles, etc.

I hope these Python interview questions and answers will help you.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.