KEMBAR78
Python Q&A for Data Engineers | PDF | Function (Mathematics) | String (Computer Science)
0% found this document useful (0 votes)
15 views127 pages

Python Q&A for Data Engineers

Uploaded by

awsdevopsgroup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views127 pages

Python Q&A for Data Engineers

Uploaded by

awsdevopsgroup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.

COM]

Page 1 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Contents
1. What is Python? .......................................................................................................................................................... 10
2. What are the key features of Python? ........................................................................................................................ 10
3. What are variables in Python? .................................................................................................................................... 11
4. What are data types in Python? .................................................................................................................................. 12
5. What is a list in Python? .............................................................................................................................................. 12
6. What is a tuple in Python? .......................................................................................................................................... 12
7. What is a dictionary in Python? .................................................................................................................................. 13
8. What is a set in Python?.............................................................................................................................................. 13
9. What is the difference between list and tuple in Python?.......................................................................................... 13
10. How do you write comments in Python? .................................................................................................................. 14
11. How is Python interpreted? ...................................................................................................................................... 14
12. What is indentation in Python and why is it important? .......................................................................................... 15
13. What is the difference between a function and a method in Python? ..................................................................... 15
14. What are arguments and parameters in Python functions? ..................................................................................... 16
15. What is the use of the return statement in Python? ................................................................................................ 16
16. What are Python loops? ............................................................................................................................................ 16
17. What is the difference between for and while loops in Python? .............................................................................. 17
18. What is a conditional statement in Python? ............................................................................................................. 17
19. What is the use of the break, continue, and pass statements in Python? ................................................................ 18
20. How do you create a class in Python?....................................................................................................................... 18
21. What is an object in Python? .................................................................................................................................... 19
22. What is inheritance in Python? ................................................................................................................................. 19
23. What is polymorphism in Python? ............................................................................................................................ 20
24. What is encapsulation in Python?............................................................................................................................. 20
25. What is abstraction in Python? ................................................................................................................................. 21
26. What is the difference between global and local variables in Python? .................................................................... 21
27. What are Python decorators and how are they used? ............................................................................................. 22
28. What is list comprehension in Python? .................................................................................................................... 23
29. What is the difference between append() and extend() in Python lists? ................................................................. 23
30. What is a module in Python? .................................................................................................................................... 23
31. What is a package in Python? ................................................................................................................................... 24
32. What is the purpose of __init__.py in Python packages? ......................................................................................... 25
33. How do you handle exceptions in Python? ............................................................................................................... 26
34. What is the difference between break, continue, and pass in Python? ................................................................... 27
35. What are Python decorators? ................................................................................................................................... 28
36. What is a Counter in Python? ................................................................................................................................... 28
37. What are closures in Python? ................................................................................................................................... 29
Page 2 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

38. What are *args and kwargs in Python?..................................................................................................................... 29


39. What is the LEGB rule in Python? ............................................................................................................................. 30
40. How can you handle file operations in Python? ....................................................................................................... 30
41. What are Python’s built-in data types? ..................................................................................................................... 31
42. What is the difference between mutable and immutable types in Python? ............................................................ 32
43. How do you define and use a function in Python? ................................................................................................... 33
44. What is duck punching (monkey patching) in Python? ............................................................................................. 33
45. What is a lambda function in Python? ...................................................................................................................... 33
46. What are Python’s magic methods? ......................................................................................................................... 34
47. What is the difference between is and == in Python? .............................................................................................. 35
48. How is memory managed in Python? ....................................................................................................................... 35
49. What is the purpose of the gc module in Python? ................................................................................................... 35
50. What are Python iterators? ....................................................................................................................................... 36
51. What is the difference between deepcopy() and copy()? ......................................................................................... 36
52. What is slicing in Python? ......................................................................................................................................... 37
53. What is the difference between append() and extend() in lists? .............................................................................. 37
54. What is the purpose of enumerate() in Python? ...................................................................................................... 38
55. What is the difference between filter(), map(), and reduce()? ................................................................................. 38
56. What is the use of zip() in Python? ........................................................................................................................... 39
57. What is recursion in Python? .................................................................................................................................... 39
58. What is a Python module? ........................................................................................................................................ 39
59. What are weak references in Python? ...................................................................................................................... 40
60. What is the super() function in Python? ................................................................................................................... 40
61. What is collections.deque and why is it better than a list for some use cases? ....................................................... 41
62. What are named tuples and why are they useful? ................................................................................................... 41
63. What are Python comprehensions?.......................................................................................................................... 41
64. What is the difference between @staticmethod and @classmethod in Python? .................................................... 42
65. What are Python annotations? ................................................................................................................................. 43
66. What are type hints and why are they useful in Python? ......................................................................................... 43
67. What is a namespace in Python? .............................................................................................................................. 44
68. What is the difference between global and local variables? .................................................................................... 44
69. How does exception handling work in Python? ........................................................................................................ 45
70. Implement a List Sorting Function Without Using Built-in Methods ........................................................................ 45
71. Find Missing Numbers in a List The second question was to find all the numbers missing from a given list in the
range between the minimum and maximum values ...................................................................................................... 46
72.Please write a program which prints all permutations of [1,2,3] .............................................................................. 46
73.Please write a program which count and print the numbers of each character in a string input by console. .......... 46

Page 3 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

74.With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements
are intersection of the above given lists. ........................................................................................................................ 47
75.By using list comprehension, please write a program to print the list after removing the value 24 in
[12,24,35,24,88,120,155]. ............................................................................................................................................... 47
76.By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in
[12,24,35,70,88,120,155]. ............................................................................................................................................... 47
77.Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. ................... 47
78.Please write a program to shuffle and print the list [3,6,7,8]. ................................................................................... 47
79.Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and
the object is in ["Hockey","Football"]. ............................................................................................................................ 48
80.Please write a program to print the running time of execution of "1+1" for 100 times. ........................................... 48
81.Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!"
........................................................................................................................................................................................ 48
82. What is the difference between repr() and str() in Python? ..................................................................................... 49
83. What is None in Python? .......................................................................................................................................... 49
84. What is a recursive lambda function? ....................................................................................................................... 49
85. What is a ternary operator in Python? ..................................................................................................................... 50
86. What are Python assertions? .................................................................................................................................... 50
87. What is the use of zip() in Python? ........................................................................................................................... 50
88. What is the purpose of dir() in Python? .................................................................................................................... 51
89. What is the map() function in Python? ..................................................................................................................... 51
90. What is the filter() function in Python? .................................................................................................................... 51
91. What is the reduce() function in Python? ................................................................................................................. 52
92. What is a frozenset in Python? ................................................................................................................................. 52
93. What is the difference between yield and return in Python? ................................................................................... 52
94. What is the with statement in Python and why is it used?....................................................................................... 53
95.Write a Python program to do arithmetical operations addition and division. ......................................................... 53
96.Write a Python program to find the area of a triangle............................................................................................... 54
97.Write a Python program to swap two variables. ........................................................................................................ 54
98.Write a Python program to generate a random number. .......................................................................................... 55
99.Write a Python program to convert kilometers to miles............................................................................................ 55
100.Write a Python program to convert Celsius to Fahrenheit....................................................................................... 55
101.Write a Python program to display calendar. ........................................................................................................... 55
102.Write a Python program to solve quadratic equation. ............................................................................................. 56
103.Write a Python program to swap two variables without temp variable. ................................................................. 57
104.Write a Python Program to Check if a Number is Positive, Negative or Zero. ......................................................... 57
105.Write a Python Program to Check if a Number is Odd or Even. ............................................................................... 57
106.Write a Python Program to Check Leap Year. ........................................................................................................... 58
107.Write a Python Program to Check Prime Number.................................................................................................... 58
Page 4 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

108.Write a Python Program to Print all Prime Numbers in an Interval of 1-10............................................................. 59


109.Write a Python Program to Find the Factorial of a Number. .................................................................................... 59
110.Write a Python Program to Display the multiplication Table. .................................................................................. 60
111.Write a Python Program to Print the Fibonacci sequence. ...................................................................................... 60
112.Write a Python Program to Check Armstrong Number? .......................................................................................... 61
113.Write a Python Program to Find Armstrong Number in an Interval. ....................................................................... 62
114.Write a Python Program to Find the Sum of Natural Numbers. .............................................................................. 62
115.Write a Python Program to Find LCM....................................................................................................................... 63
116.Write a Python Program to Find HCF. ....................................................................................................................... 63
117.Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal? ................................................... 64
118.Write a Python Program To Find ASCII value of a character. .................................................................................... 65
119.Write a Python Program to Display Fibonacci Sequence Using Recursion............................................................... 65
120.Write a Python Program to Find Factorial of Number Using Recursion. .................................................................. 66
121.Write a Python Program to calculate the natural logarithm of any number. ........................................................... 66
122.Write a Python Program for cube sum of first n natural numbers? ......................................................................... 67
123.Write a Python Program to find sum of array. ......................................................................................................... 68
124.Write a Python Program to find largest element in an array.................................................................................... 69
125.Write a Python Program for array rotation. ............................................................................................................. 69
126.Write a Python Program to Split the array and add the first part to the end? ........................................................ 70
127.Write a Python Program to check if given array is Monotonic................................................................................. 70
128.Write a Python Program to Transpose a Matrix. ...................................................................................................... 71
129.Write a Python Program to Sort Words in Alphabetic Order. .................................................................................. 71
130.Write a Python Program to Remove Punctuation From a String. ............................................................................ 72
131.Write a Python program to check if the given number is a Disarium Number. ....................................................... 72
132.Write a Python program to print all disarium numbers between 1 to 100.............................................................. 73
133.Write a Python program to check if the given number is Happy Number. .............................................................. 73
134.Write a Python program to print all happy numbers between 1 and 100. .............................................................. 74
135.Write a Python program to determine whether the given number is a Harshad Number. ..................................... 74
136.Write a Python program to print all pronic numbers between 1 and 100. .............................................................. 75
137.Write a Python program to find sum of elements in list. ......................................................................................... 75
138.Write a Python program to Multiply all numbers in the list. ................................................................................... 76
139.Write a Python program to find smallest number in a list. ...................................................................................... 76
140.Write a Python program to find largest number in a list. ........................................................................................ 76
141.Write a Python program to find second largest number in a list. ............................................................................ 77
142.Write a Python program to find N largest elements from a list. .............................................................................. 77
143.Write a Python program to print even numbers in a list.......................................................................................... 77
144.Write a Python program to print odd numbers in a List. ......................................................................................... 78

Page 5 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

145.Write a Python program to Remove empty List from List. ....................................................................................... 78


146.Write a Python program to Cloning or Copying a list. .............................................................................................. 78
147.Write a Python program to Count occurrences of an element in a list.................................................................... 79
148.Write a Python program to find words which are greater than given length k. ...................................................... 79
149.Write a Python program for removing i th character from a string. ........................................................................ 80
150.Write a Python program to split and join a string. ................................................................................................... 80
151.Write a Python program to check if a given string is binary string or not................................................................ 81
152.Write a Python program to find uncommon words from two Strings. .................................................................... 81
153.Write a Python program to find all duplicate characters in string. .......................................................................... 82
154.Write a Python Program to check if a string contains any special character............................................................ 82
155.Write a Python program to Extract Unique dictionary values. ................................................................................ 83
156.Write a Python program to find the sum of all items in a dictionary. ...................................................................... 84
157.Write a Python program to Merging two Dictionaries. ............................................................................................ 84
158.Write a Python program to convert key-values list to flat dictionary....................................................................... 85
159.Write a Python program to insertion at the beginning in OrderedDict. .................................................................. 85
160.Write a Python program to sort Python Dictionaries by Key or Value ..................................................................... 85
161.Write a program that accepts a sentence and calculate the number of letters and digits. ..................................... 86
162.Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0
and n. .............................................................................................................................................................................. 87
163.Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which
can print "Male" for Male class and "Female" for Female class. .................................................................................... 87
164.Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"]
and the object is in ["Hockey","Football"]. ..................................................................................................................... 88
165.Please write a binary search function which searches an item in a sorted list. The function should return the
index of element to be searched in the list..................................................................................................................... 88
166.Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n
in comma separated form while n is input by console. .................................................................................................. 89
167.Please write a program using generator to print the even numbers between 0 and n in comma separated form
while n is input by console. ............................................................................................................................................. 89
168.Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with
a given n input by console............................................................................................................................................... 90
169.please write program to print the user name of a given email address. Both user names and company names are
composed of letters only. ................................................................................................................................................ 90
170. Create a class called Shape with a method area() that returns 0. Then, create a subclass called Square that takes
the side length as input and overrides the area() method to return the area of the square. ........................................ 91
171.The "Reverser" takes a string as input and returns that string in reverse order, with the opposite case. ............... 91
172.Write a function that calculates the factorial of a number recursively. ................................................................... 92
173.Create a function that takes a string and returns a string in which each character is repeated once..................... 92
174.Create a function that reverses a boolean value and returns the string "boolean expected" if another variable
type is given. ................................................................................................................................................................... 93

Page 6 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

175.Create a function that returns the thickness (in meters) of a piece of paper after folding it n number of times. The
paper starts off with a thickness of 0.5mm. ................................................................................................................... 93
176.Create a function that takes a single string as argument and returns an ordered list containing the indices of all
capital letters in the string. ............................................................................................................................................. 94
177.Using list comprehensions, create a function that finds all even numbers from 1 to the given number. ............... 95
178.Create a function that takes a list of strings and integers, and filters out the list so that it returns a list of integers
only. ................................................................................................................................................................................. 95
179.Given a list of numbers, create a function which returns the list but with each element's index in the list added to
itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc... ..................................... 96
180.Create a function that takes the height and radius of a cone as arguments and returns the volume of the cone
rounded to the nearest hundredth. See the resources tab for the formula. .................................................................. 96
181.Create a function that takes a list of numbers between 1 and 10 (excluding one number) and returns the missing
number. ........................................................................................................................................................................... 97
182.Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove
the first element of the list. The function should then return the updated list. ............................................................ 97
183.Create the function that takes a list of dictionaries and returns the sum of people's budgets............................... 98
185.Create a function that takes a string and returns a string with its letters in alphabetical order. ............................. 99
186.Write a function that takes a list of elements and returns only the integers. ......................................................... 99
187.Create a function that takes three parameters where: - x is the start of the range (inclusive). - y is the end of the
range (inclusive). - n is the divisor to be checked against. Return an ordered list with numbers in the range that are
divisible by the third parameter n. Return an empty list if there are no numbers that are divisible by n. .................. 100
188.Create a function that takes in two lists and returns True if the second list follows the first list by one element,
and False otherwise. In other words, determine if the second list is the first list shifted to the right by 1. ................ 100
189.A group of friends have decided to start a secret society. The name will be the first letter of each of their names,
sorted in alphabetical order. Create a function that takes in a list of names and returns the name of the secret society.
...................................................................................................................................................................................... 101
190.Create a function that takes a string and returns True or False, depending on whether the characters are in order
or not............................................................................................................................................................................. 102
191.Create a function that squares every digit of a number. ....................................................................................... 102
192.Create a function that sorts a list and removes all duplicate items from it. .......................................................... 103
193.Create a function that returns the mean of all digits. ............................................................................................ 103
194.Write a function that creates a dictionary with each (key, value) pair being the (lower case, upper case) versions
of a letter, respectively. ................................................................................................................................................. 104
195.Write a function that converts a dictionary into a list of keys-values tuples. ........................................................ 104
196.Create a function that takes three integer arguments (a, b, c) and returns the amount of integers which are of
equal value. ................................................................................................................................................................... 105
197.Create a function that takes a list of strings and return a list, sorted from shortest to longest. ........................... 106
198.Create a function that takes a list of numbers and return the number that's unique. .......................................... 106
199.You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with
word1. If a string is longer than the other, append the additional letters onto the end of the merged string. ........... 107

Page 7 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

200.For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e, t is concatenated with itself
one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2
...................................................................................................................................................................................... 108
201. You have a list of kids, and each kid has a certain number of candies. You're also given some extra candies. For
each kid, check: If we give all the extra candies to that kid, will they have the most candies (or equal to the most)
compared to the others? Return a list of True or False for each kid. ............................................................................ 108
202.You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be
planted in adjacent plots. ............................................................................................................................................. 109
203.Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and
they can appear in both lower and upper cases, more than once. .............................................................................. 110
204.Given an input string s, reverse the order of the words. ....................................................................................... 110
205.Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero
elements. ...................................................................................................................................................................... 111
206.Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a
new string that is formed from the original string by deleting some (can be none) of the characters without disturbing
the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). ....... 111
207.You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array
whose sum equals k and remove them from the array. Return the maximum number of operations you can perform
on the array. .................................................................................................................................................................. 112
208.You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose
length is equal to k that has the maximum average value and return this value. Any answer with a calculation error
less than 10-5 will be accepted. .................................................................................................................................... 112
209.Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. ......................................................................................................... 113
210.Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you
can flip at most k 0's...................................................................................................................................................... 113
211.Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty
subarray containing only 1's in the resulting array. Return 0 if there is no such subarray............................................ 114
212.There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts
his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where gain[i] is the net gain in
altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point...................................... 114
213.Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the
sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's
right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This
also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1........... 115
214.Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0] is a list of
all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct integers in nums2
which are not present in nums1. Note that the integers in the lists may be returned in any order. ........................... 115
215.Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or
false otherwise. ............................................................................................................................................................. 116
216.You are given a string s, which contains stars *. In one operation, you can: Choose a star in s. Remove the closest
non-star character to its left, as well as remove the star itself. Return the string after all stars have been removed. 116

Page 8 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

217.A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-
alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and
numbers. Given a string s, return true if it is a palindrome, or false otherwise. .......................................................... 116
218.Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. ......................... 117
219.Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a
maximal substring consisting of non-space characters only. ........................................................................................ 117
220.Write a function to find the longest common prefix string amongst an array of strings ....................................... 117
221.How do you count the number of 1s and 0s in a Python list? ............................................................................... 118
222. Write a Python program to print all numbers that occur more than once in the list. .......................................... 118
223. Write a Python class named person with attributes name and age. Create an object of this class with name
"john" and age 25, and print the name of the person. ................................................................................................. 119
224.Write a Python program to extract all consecutive digits from a string and calculate their total sum. ................ 119
225.Please write a program to randomly print a integer number between 7 and 15 inclusive. .................................. 120
226.Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1
and 1000 inclusive......................................................................................................................................................... 120
227.Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive
using random module and list comprehension. ........................................................................................................... 120
228.Please generate a random float where the value is between 5 and 95 using Python math module. ................... 120
229.Please write a binary search function which searches an item in a sorted list. The function should return the
index of element to be searched in the list................................................................................................................... 121
230.Please write a program which accepts basic mathematic expression from console and print the evaluation result.
...................................................................................................................................................................................... 121
231.Please write assert statements to verify that every number in the list [2,4,6,8] is even. ..................................... 122
232.Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n
in comma separated form while n is input by console. ................................................................................................ 122
233.Define a custom exception class which takes a string message as attribute. ........................................................ 122
234.Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as
argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
...................................................................................................................................................................................... 123
235.Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a
method which can compute the area. .......................................................................................................................... 123
236.Define a class named Circle which can be constructed by a radius. The Circle class has a method which can
compute the area. ......................................................................................................................................................... 123
237.Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both
included). ...................................................................................................................................................................... 124
238.Write a program to generate and print another tuple whose values are even numbers in the given tuple
(1,2,3,4,5,6,7,8,9,10). .................................................................................................................................................... 124
239. How does Python handle memory management?. .............................................................................................. 124
240. What is the difference between a list and a generator in Python? ...................................................................... 124
241. How can you handle missing values in a dataset using Python? .......................................................................... 125
242. What are Python generators? How are they different from regular functions? ................................................... 125

Page 9 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

1. What is Python?

Python is a high-level, open-source programming language created by Guido van Rossum in 1991. It has
simple, readable syntax and is widely used for web development, data engineering, data science, AI,
automation, and more. Python is beginner-friendly and used by top companies like Google, Netflix, and
Instagram.

2. What are the key features of Python?

Key Features of Python


1. Simple & Readable Syntax
• Easy to learn and write.
• Code looks like plain English.
print("Hello, World!")

2. Open Source
• Free to use, modify, and distribute.
• Huge community support.

3. Interpreted Language
• Code is executed line by line.
• No need for compilation before running.

4. Dynamically Typed
• No need to declare variable types.

x = 10 # int
x = "Hello" # str (same variable, different type)

5. Object-Oriented
• Supports classes, objects, inheritance, encapsulation.

class Dog:
def bark(self):
print("Woof!")

6. Extensive Standard Library


• Built-in modules for file handling, math, web, databases, etc.

import math
print(math.sqrt(16))

7. Cross-Platform
• Runs on Windows, macOS, Linux, etc.
• Write once, run anywhere (with Python installed).

Page 10 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

8. Supports Multiple Paradigms


• Procedural
• Object-Oriented
• Functional (e.g., map(), lambda, filter())

9. Huge Ecosystem of Libraries


• For data science: pandas, numpy, matplotlib
• For web: Django, Flask
• For AI/ML: scikit-learn, TensorFlow, PyTorch

10. Integration Friendly


• Easily integrates with C/C++, Java, .NET, databases, and web services.

Summary

Feature Description
Easy Syntax Readable and beginner-friendly
Open Source Free and community-supported
Interpreted Line-by-line execution
Dynamically Typed No type declaration needed
Object-Oriented Supports OOP concepts
Standard Library Comes with built-in modules
Cross-Platform Works on all major OS
Multi-Paradigm OOP, Procedural, Functional
Rich Ecosystem Thousands of third-party libraries
Integration Support Works well with other languages/tools

3. What are variables in Python?

Variables in Python are names used to store data values.


They act as containers for holding information that can be used and changed later in the program.

Example:

• x is a variable storing an integer.


• name is a variable storing a string.

Page 11 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

4. What are data types in Python?

1. Numeric Types
• int: Whole numbers → x = 10
• float: Decimal numbers → y = 3.14
• complex: Complex numbers → z = 2 + 3j
2. Text Type
• str: Text → name = "Python"
3. Boolean Type
• bool: Logical values → True or False
4. Sequence Types
• list: Ordered & changeable → fruits = ["apple", "banana"]
• tuple: Ordered & unchangeable → point = (1, 2)
• range: Sequence of numbers → range(0, 5)
5. Set Types
• set: Unordered, unique items → {1, 2, 3}
• frozenset: Immutable set → frozenset([1, 2])
6. Mapping Type
• dict: Key-value pairs → {"name": "Naresh"}
7. None Type
• NoneType: Represents no value → x = None

5. What is a list in Python?

A list in Python is an ordered, mutable (changeable) collection of items.


It can hold elements of different data types like numbers, strings, or even other lists.

• You can add, remove, or change items in a list.


• Lists are defined using square brackets [].

6. What is a tuple in Python?

A tuple in Python is an ordered, immutable (unchangeable) collection of items.


It is similar to a list, but once created, its values cannot be modified.

• Tuples are defined using parentheses ().


• They are often used for fixed data like coordinates, dates, etc.
Page 12 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

7. What is a dictionary in Python?

A dictionary in Python is an unordered, mutable collection of key-value pairs.


Each key must be unique, and it is used to access its corresponding value.

• Defined using curly braces {}.


• You can add, update, or delete key-value pairs.

8. What is a set in Python?

A set in Python is an unordered, mutable collection of unique elements (no duplicates allowed).
It is commonly used for membership tests, removing duplicates, and mathematical operations like union or
intersection.

• Defined using curly braces {} or the set() function.


• Does not allow duplicate values.

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

Tuple vs List in Python

Feature List Tuple


Syntax my_list = [1, 2, 3] my_tuple = (1, 2, 3)
❌ No – Immutable
Mutable? ✅ Yes – You can change values
(unchangeable)
More built-in methods (e.g.,
Methods Fewer methods
append(), remove())
Performance Slightly slower due to mutability Slightly faster (less overhead)
Use Case When you need to modify data When data should not change
Can contain different data
✅ Yes ✅ Yes
types?

Use Case:
• Use a list when you need a flexible, changeable collection.
• Use a tuple when you need a fixed, read-only collection for better performance and safety.

Page 13 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

10. How do you write comments in Python?

In Python, you write comments using the # symbol.


Comments are ignored by the interpreter and are used to explain code.

Example:

For multi-line comments, you can use # on each line or use triple quotes (''' or """) as a workaround:

11. How is Python interpreted?

Python is an interpreted language, meaning the code is executed line by line by the Python interpreter, not
compiled into machine code beforehand.
What happens when you run a Python script:
1. You write code (.py file).
2. The Python interpreter reads and converts it to bytecode.
3. The Python Virtual Machine (PVM) executes the bytecode line by line.
This makes Python:
• Easy to debug
• Portable across platforms
• Slightly slower than compiled languages like C/C++

No need for manual compilation — just run:

Page 14 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

12. What is indentation in Python and why is it important?

Indentation in Python refers to the spaces or tabs used at the beginning of a line to define code blocks.
It is mandatory in Python and replaces braces ({}) used in other languages.

Why It’s Important:


• It tells Python which statements belong together (like inside a loop or function).
• Improper indentation will cause an IndentationError.
Correct indentation = working code
Wrong indentation = syntax error

13. What is the difference between a function and a method in Python?

The key difference between a function and a method in Python lies in how they are defined and used:
Function

• A function is a block of reusable code defined using def.


• It is independent and not tied to any object.
Example:

Method

• A method is a function that is associated with an object (i.e., defined inside a class).
• It is called on an object using dot notation.
Example:

Summary:

Feature Function Method


Defined with def ✅ Yes ✅ Yes
Belongs to object ❌ No ✅ Yes (inside a class)
Called as func() object.method()

Page 15 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

14. What are arguments and parameters in Python functions?

Parameters are the names you define in a function when you write it.
Arguments are the actual values you pass to the function when calling it.

15. What is the use of the return statement in Python?


The return statement in Python is used in a function to send a value back to the place where the function was
called.

It ends the function and passes the result to the caller.

16. What are Python loops?

Loops in Python are used to run a block of code multiple times.


Python supports two main types of loops: for and while.
The for loop is used when you want to repeat something for a specific number of times or through items in a
sequence like a list:

Page 16 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

17. What is the difference between for and while loops in Python?

The for loop and while loop are both used to repeat actions, but they are used in different situations.
A for loop is best when you know in advance how many times you want to repeat something.
It works well with lists, strings, and ranges:

18. What is a conditional statement in Python?

Conditional statements are used to run certain blocks of code only when specific conditions are met.

Python uses if, elif, and else for this:

Page 17 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

19. What is the use of the break, continue, and pass statements in Python?

20. How do you create a class in Python?

A class in Python is a blueprint for creating objects. It defines the structure and behavior (methods and
variables) of an object.
You create a class using the class keyword:

The __init__ method is the constructor and runs when a new object is created.
You can create an object like p1 = Person("Alice") and call its method using p1.greet().
Classes help in object-oriented programming and allow you to create reusable code.

Page 18 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

21. What is an object in Python?

An object in Python is an instance of a class.


When you create a class, you’re just defining the structure.
But when you create an object using that class, you get a working version with real values.

Here, dog1 is an object of the Dog class.


It has its own copy of data and can use class methods. In Python, almost everything is an object—strings, lists,
functions, and even classes.
Objects make code modular, reusable, and organized.

22. What is inheritance in Python?

Inheritance in Python allows one class (called a child or subclass) to get features from another class (called a
parent or base class).

It helps in reusing code and building relationships between classes. Here’s a basic example:

In this example, the Dog class inherits from Animal, so it can use the speak() method.
Inheritance supports code reuse and helps organize code better when working with related classes.

Page 19 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

23. What is polymorphism in Python?

Polymorphism means “many forms”.

In Python, polymorphism allows different classes to have methods with the same name, but different behavior.
For example, if two classes have a method named speak(), you can call speak() on any object, and it will
behave according to its class:

Each object knows how to perform its version of the method.


Polymorphism makes code flexible and helps when writing functions that can work with multiple types of
objects.

24. What is encapsulation in Python?

Encapsulation is a concept in object-oriented programming that hides the internal details of a class and
protects data from outside access.
In Python, we use private variables (with a single or double underscore _ or __) to indicate that they should not
be accessed directly:

In this example, __name is private.

We access it using the get_name() method.

Encapsulation helps keep your data safe, and only allows access through defined methods, making your code
more secure and easier to maintain.

Page 20 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

25. What is abstraction in Python?

Abstraction means showing only the essential features and hiding the unnecessary details.
It helps reduce complexity and allows you to focus on what an object does, not how it does it.
In Python, abstraction is often implemented using abstract classes and methods from the abc module:

Here, Animal is an abstract class, and make_sound() must be implemented in any child class.
Abstraction helps in designing clean interfaces and focusing on high-level functionality.

26. What is the difference between global and local variables in Python?

In Python, a local variable is a variable that is declared inside a function and can only be used within that
function.

It exists temporarily while the function runs. A global variable, on the other hand, is declared outside of all
functions and can be used anywhere in the code.

In this code, x is global and y is local.


If you want to modify a global variable inside a function, you must use the global keyword.
Without that, Python will treat it as a local variable, which could lead to errors.

Page 21 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

27. What are Python decorators and how are they used?

A decorator is a function that wraps another function to modify or extend its behavior without changing the
original function’s code.

• Decorators are often used for:


• Logging
• Authentication
• Performance measurement
• Caching
• Access control

Syntax of a Decorator

Example: Create a Custom Decorator

Goal: Log when a function is called

Page 22 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

28. What is list comprehension in Python?

List comprehension is a concise way to create lists in Python.


Instead of using loops, you can use a single line of code.
It improves readability and performance. Here’s a basic example

List comprehensions are useful when you want to transform or filter data quickly. They make your code shorter,
cleaner, and easier to understand than using a full for loop.

29. What is the difference between append() and extend() in Python lists?

Both append() and extend() are used to add elements to a list, but they work differently.

append() adds a single element to the end of the list, while extend() adds all elements from another list (or
iterable).

As you can see, append() adds the entire list as a single element, while extend() breaks it and adds each item.
Use append() for one item and extend() for multiple items from another list.

30. What is a module in Python?

A module in Python is a file that contains Python code. It can include functions, variables, and classes.
You can import a module into another script to reuse the code.

Python has many built-in modules like math, datetime, and os. You can also create your own custom modules
by saving your code in a .py file.

Using modules helps organize code better, keeps it cleaner, and promotes reuse.
When your codebase grows, splitting functionality into modules makes it easier to manage and maintain

Page 23 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

31. What is a package in Python?

A package in Python is a way of organizing related modules into a directory hierarchy. It allows you to group
related code together, making your project more modular, manageable, and reusable.

Technically, a package is just a folder containing a special __init__.py file, and it can include multiple
modules (Python .py files) and sub-packages.

Example: Creating a Simple Package


Let's say you want to create a package named math_utils with some math operations:

Using the Package:

Page 24 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Summary:

• A module is a single .py file.


• A package is a folder with an __init__.py, containing modules or sub-packages.
• Packages help organize code in large applications.

32. What is the purpose of __init__.py in Python packages?

__init__.py is used to:


1. Mark a folder as a Python package
2. Initialize package-level variables or logic
3. Simplify imports from submodules
4. Control what gets imported with from package import *

Example:

Page 25 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Usage:

Without __init__.py, Python may not treat the folder as a package (especially in older versions).
It also helps group and expose functions cleanly.

33. How do you handle exceptions in Python?

In Python, you handle errors and exceptions using try, except, and optionally finally.
This allows your program to continue running even if something goes wrong. Here's an example:

The try block runs the risky code.


If there’s an error, Python checks for a matching except block.
The finally block always runs, whether an error occurred or not. Exception handling makes your programs more
robust and user-friendly.

Page 26 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

34. What is the difference between break, continue, and pass in Python?

In Python, break, continue, and pass are control flow statements, but each one serves a different purpose.
break: It is used to exit a loop completely, even if the loop condition is still true.
Once break is encountered, the loop stops running.

continue: It skips the current iteration and moves to the next one without stopping the loop.

pass: It does nothing and is used as a placeholder where code is required syntactically but no action is needed.

Page 27 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

35. What are Python decorators?

A decorator in Python is a function that takes another function as input and adds extra functionality to it,
without changing its original structure.

It is often used to modify the behavior of a function or method dynamically

Here, @decorator wraps the greet() function and adds extra code before and after it. Decorators are used often
in logging, authentication, timing, and access control. They help you write cleaner, reusable, and more
readable code.

36. What is a Counter in Python?

Counter is a class from the collections module that helps count occurrences of elements in an iterable. It
returns a dictionary-like object where elements are stored as keys and counts as values.

It supports most dictionary operations and provides extra methods like .most_common() and .elements() for
retrieving data in specific formats. It is extremely useful for statistics, frequency analysis, and text processing.

Page 28 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

37. What are closures in Python?

Closures are functions that remember the values of variables from their enclosing lexical scope even after that
scope has finished executing. In other words, a closure allows a function to access variables from an outer
function that has already returned.

In the above code, the function inner() forms a closure—it remembers the variable msg from its enclosing
function outer(). Closures are useful for building function factories, decorators, and keeping state in a clean
and elegant way.

38. What are *args and kwargs in Python?

In Python, *args and **kwargs are used in function definitions to allow the function to accept a variable number
of arguments.

*args collects extra positional arguments into a tuple.


**kwargs collects extra keyword arguments into a dictionary.

These features make your functions flexible and reusable. You can call them with different numbers of
parameters without changing the function definition.

Page 29 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

39. What is the LEGB rule in Python?

LEGB stands for Local → Enclosing → Global → Built-in, and it defines the order in which Python searches for
variables:
Local: Names inside the current function.
Enclosing: Names in outer (but not global) functions if nested.
Global: Names defined at the top-level of a script or module.
Built-in: Python’s predefined names like len() or str.

40. How can you handle file operations in Python?

Python provides built-in functions to perform file operations such as reading, writing, and appending. The core
function used is open().
Basic Syntax:

Common File Modes:

Page 30 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Why use with open(...)?

Using with automatically closes the file even if an error occurs — it's the recommended way.

Tips:

• Always handle file paths properly (use os.path or pathlib)


• Use exception handling (try...except) for robust code

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

Python provides several built-in data types to handle different kinds of data. These are grouped into categories:

1. Numeric Types
Used to store numbers.
• int – Integer (e.g., 10)
• float – Floating-point number (e.g., 3.14)
• complex – Complex number (e.g., 2 + 3j)

2. Text Type
• str – String (e.g., "Hello World")

3. Sequence Types
Ordered collections of items.
• list – Mutable sequence (e.g., [1, 2, 3])
• tuple – Immutable sequence (e.g., (1, 2, 3))
• range – Sequence of numbers (e.g., range(5))

Page 31 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

4. Mapping Type
• dict – Key-value pairs (e.g., {"name": "Naresh", "age": 30})

5. Set Types
Unordered collections of unique items.
• set – Mutable set (e.g., {1, 2, 3})
• frozenset – Immutable set

6. Boolean Type
• bool – Represents True or False

7. Binary Types
Used for binary data.
• bytes
• bytearray
• memoryview

8. None Type
• None – Represents the absence of a value

Example:

42. What is the difference between mutable and immutable types in Python?

Mutable types can be changed after creation. Examples include list, dict, and set. You can add, remove, or
change elements in these types.

Immutable types cannot be changed once created. Examples include int, float, str, and tuple. If you try to
modify them, Python creates a new object instead

Knowing which types are mutable and which are not helps you avoid bugs, especially when passing variables
into functions. It also affects performance and how memory is managed.
Page 32 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

43. How do you define and use a function in Python?

To define a function in Python, you use the def keyword followed by the function name and parentheses. You
can pass arguments into the function and return values using the return statemen

Functions make your code reusable and organized. Instead of repeating the same logic, you put it in a function
and call it whenever needed. You can also have default arguments, variable-length arguments, and even
functions inside functions.

44. What is duck punching (monkey patching) in Python?

Monkey patching (or duck punching) is the practice of changing or extending the behavior of libraries, classes,
or modules at runtime.

This can be useful for testing or hotfixes but is generally discouraged in production code because it can lead to
unpredictable behavior and maintenance challenges.

45. What is a lambda function in Python?

A lambda function is a small, anonymous function defined using the lambda keyword.
It can have any number of arguments but only one expression.

Lambda functions are often used when you need a short function for a short time — usually passed as an
argument.

Syntax:

Example:
Page 33 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Use Case:

46. What are Python’s magic methods?

Magic methods in Python are special methods with double underscores at the beginning and end of their
names. They’re also known as dunder methods. Python uses these methods to perform operator overloading
and other behaviors internally.

Some common magic methods are:

__init__: Constructor, called when an object is created.

__str__: Returns a string representation of the object.

__len__: Returns the length using len().

__add__: Defines behavior for +.

Magic methods make classes act like built-in types, improving readability and flexibility

Page 34 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

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

In Python:

== checks if values of two variables are equal.


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

48. How is memory managed in Python?

Python uses a combination of reference counting and a garbage collector to manage memory.
Each object has a reference count: when the count reaches zero, it is deleted.
Python also uses a garbage collector to handle circular references, where two objects refer to each other but
are no longer used.
You don’t usually need to manage memory manually. Python handles it for you. But you can still check or
influence it using the gc module:

Also, memory is allocated in private heaps managed by the Python interpreter. Efficient memory handling is
part of Python’s design to help developers focus on logic instead of low-level resource management.

49. What is the purpose of the gc module in Python?

The gc (garbage collection) module provides access to Python's automatic memory management. It allows you
to manually trigger garbage collection, monitor objects that aren’t being collected, and control collection
thresholds.

It’s particularly useful when dealing with circular references — where two objects refer to each other,
preventing their reference count from dropping to zero. The gc module helps identify and clean these
unreachable objects.

Page 35 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

50. What are Python iterators?

An iterator in Python is an object that allows you to loop over its elements, one at a time. It must implement the
__iter__() and __next__() methods. You can get an iterator from any iterable (like lists, tuples, sets) using the
iter() function. Then, you use next() to get the next item.

When there are no more items, next() raises a StopIteration error. Iterators are memory-efficient because they
don’t store the whole sequence in memory, which is helpful for large datasets or file reading.

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

In Python, copy() and deepcopy() both come from the copy module and are used to duplicate objects, but they
behave differently:

copy.copy() creates a shallow copy of an object. It copies the outer object, but not the nested objects inside it.
So changes to inner objects affect both copies.

copy.deepcopy() creates a completely independent clone, including all nested objects. Changes to one object
do not affect the other.

Page 36 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

52. What is slicing in Python?

Slicing in Python lets you extract a portion of a list, string, or tuple using a range of indexes. The basic syntax is
object[start:stop:step].

start is the index to begin from (inclusive),

stop is where to end (exclusive)

step tells how many items to skip.

Slicing is powerful for reversing sequences, picking even-indexed items, or extracting parts of text. It works with
strings to

53. What is the difference between append() and extend() in lists?

Both append() and extend() are used to add elements to a list, but they do it differently:

append() adds a single element to the end of the list, even if it’s another list.

extend() takes an iterable and adds each element from it to the list.

So, append() adds the whole object, while extend() breaks it apart and adds each item individually. Use
append() when you want to keep an item together; use extend() when you want to expand the list.

Page 37 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

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

The enumerate() function is used when you need both the index and value while looping over an iterable. It adds
a counter to the iterable and returns it as an enumerate object, which you can convert into a list or use in a
loop.

This is much cleaner than using range(len(fruits)). You can also start the index at a custom number by using
enumerate(fruits, start=1). It’s helpful when you’re processing lists, keeping track of positions, or labeling items
in a report or UI.

55. What is the difference between filter(), map(), and reduce()?

All three are functional programming tools in Python:

map() applies a function to every item in an iterable and returns a new iterable.

filter() applies a function that returns True or False, and only keeps items where the function returns True.

reduce() repeatedly applies a function to accumulate a result (from functools module).

map() transforms data, filter() selects data, and reduce() combines data. They help write clean, short code for
data processing.

Page 38 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

56. What is the use of zip() in Python?

The zip() function is used to combine two or more iterables into a single iterable of tuples, where the i-th tuple
contains the i-th element from each iterable. It stops at the shortest input length.

If the input lists are of unequal length, the extra items are ignored. You can also unzip using zip(*zipped_data).

57. What is recursion in Python?

Recursion is when a function calls itself to solve a smaller part of a problem until it reaches a base case. It’s
commonly used in problems like calculating factorials, Fibonacci numbers, and tree traversals.

Every recursive function must have a base case to prevent infinite recursion. Python limits recursion depth by
default (about 1000 calls). You can check it using sys.getrecursionlimit().

Recursion makes some problems easier to solve, though it may use more memory than loops.

58. What is a Python module?

A Python module is a single .py file that contains functions, classes, or variables you can reuse in other
programs.

Example:

Page 39 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Usage in another file:

59. What are weak references in Python?

Weak references allow Python to refer to an object without increasing its reference count. This means the
object can still be garbage-collected, which is useful when managing caches or graphs where circular
references can occur.

60. What is the super() function in Python?

The super() function returns a proxy object that delegates method calls to a parent or sibling class. It’s
commonly used in class constructors (__init__) to ensure proper initialization in inheritance chains.

Using super() helps support maintainable, extensible code and is critical in multiple inheritance where calling
the correct parent method matters.

Page 40 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

61. What is collections.deque and why is it better than a list for some use cases?

collections.deque (double-ended queue) is a part of Python’s standard collections module. It is a specialized


list-like container optimized for fast appends and pops from both ends.

While Python lists are efficient for append and pop operations at the end, they are slow when inserting or
deleting items at the beginning because all elements must be shifted.

deque solves this by using a doubly linked list internally, allowing O(1) operations on both ends:

It is ideal for queue and stack implementations, sliding windows, and breadth-first searches.

62. What are named tuples and why are they useful?

A named tuple is a factory function in the collections module that returns a subclass of tuple with named
fields. This makes your code more readable and self-documenting, while still being as memory-efficient as a
regular tuple.

Use namedtuple when you need immutable data structures with readable fields—ideal for data modeling,
configuration, and return values.

63. What are Python comprehensions?

Python comprehensions are a concise way to create lists, sets, or dictionaries using a single line of code. They
are often used as a more readable alternative to loops.

Example of list comprehension:

This creates [0, 1, 4, 9, 16]. Similarly, you can use:

Set comprehension: {x*x for x in range(5)}

Dict comprehension: {x: x*x for x in range(5)}

Page 41 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

You can also add conditions:

Comprehensions make the code cleaner and easier to read compared to using traditional loops, especially
when the operation is simple and directly maps from input to output.

64. What is the difference between @staticmethod and @classmethod in Python?

Difference Between @staticmethod and @classmethod in Python

Feature @staticmethod @classmethod


First Parameter No special first argument Takes cls as the first parameter
❌ No access to class (cls) or instance
Access to Class ✅ Has access to the class (cls)
(self)
When method doesn't need class/instance When method needs to
When to Use
data access/modify class-level data
Called Using Class or instance Class or instance

Example:

Summary:
• Use @staticmethod when the method is independent of class or instance.
• Use @classmethod when the method needs to access or modify class-level attributes.

Page 42 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

65. What are Python annotations?

Python annotations are a way to add type hints to function parameters and return types.
Introduced in PEP 484, they help improve code readability, allow static type checkers like mypy to analyze your
code, and assist with IDE autocompletion.

Annotations do not affect runtime behavior by default; they are just metadata.

Here, name is expected to be a string, and the function returns a string. You can also access annotations using
the __annotations__ attribute.

While annotations are optional, they are increasingly used in production code for documentation, validation,
and tooling support.

66. What are type hints and why are they useful in Python?

Type hints are a way to explicitly specify the data types of variables, function arguments, and return values in
Python.
Introduced in Python 3.5+, type hints improve code readability, auto-completion, and static type checking
using tools like mypy.

Example:

Here:

• a and b are expected to be integers


• The function will return an int

Why Are Type Hints Useful?

Benefit Description
🧠 Better Readability Makes the purpose of variables clearer
🤖 Tool Support Helps IDEs with auto-suggestions
🔍 Static Type Checking Tools like mypy catch type errors early
👨‍💻 Easier Maintenance Useful for large codebases and teams

Variable Hint Example:

Page 43 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

67. What is a namespace in Python?

A namespace in Python refers to a space where names are mapped to objects. Think of it as a dictionary where
the keys are variable names and the values are the objects those names refer to. Python uses namespaces to
keep track of all the names in your program, like variable names, function names, class names, etc.

There are four types of namespaces in Python:

Built-in: Contains built-in functions like print() and len().

Global: Contains names defined at the top-level of a script or module.

Enclosing: Relevant for nested functions (outer function scope).

Local: Inside a function or block

Namespaces prevent naming conflicts and help Python know which variable you’re referring to in different
parts of the program.

You can access namespaces using functions like globals() and locals().

68. What is the difference between global and local variables?

A local variable is defined inside a function and can only be used within that function. A global variable, on the
other hand, is defined outside any function and can be accessed from anywhere in the code, including inside
functions.

Page 44 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

69. How does exception handling work in Python?

Exception handling in Python is done using try, except, finally, and else blocks.
It helps your program handle unexpected errors without crashing.
You wrap the code that might throw an error in a try block, then use except to handle specific or general
exceptions.

70. Implement a List Sorting Function Without Using Built-in Methods

Approach: Used Bubble Sort – a simple comparison-based algorithm.

By repeatedly swapping adjacent elements if they are in the wrong order, we can sort the list.

Page 45 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

71. Find Missing Numbers in a List The second question was to find all the numbers missing from a given
list in the range between the minimum and maximum values

72.Please write a program which prints all permutations of [1,2,3]

Hints: Use itertools.permutations() to get permutations of list

73.Please write a program which count and print the numbers of each character in a string input by
console.

Example: If the following string is given as input to the program:

abcdefgabc

Then, the output of the program should be:

a,2 c,2 b,2 e,1 d,1 g,1 f,1

Page 46 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

74.With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose
elements are intersection of the above given lists.

75.By using list comprehension, please write a program to print the list after removing the value 24 in
[12,24,35,24,88,120,155].

76.By using list comprehension, please write a program to print the list after removing the 0th,4th,5th
numbers in [12,24,35,70,88,120,155].

77.Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].

78.Please write a program to shuffle and print the list [3,6,7,8].

Page 47 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

79.Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play",
"Love"] and the object is in ["Hockey","Football"].

80.Please write a program to print the running time of execution of "1+1" for 100 times.

81.Please write a program to compress and decompress the string "hello world!hello world!hello
world!hello world!"

Page 48 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

82. What is the difference between repr() and str() in Python?

Both repr() and str() are used to get string representations of objects, but for different purposes:
str() is for user-friendly display (e.g., print() output).
repr() is for developer-oriented output that ideally could be used to recreate the object.

83. What is None in Python?

None is a special constant in Python that represents the absence of a value or a null value.
It is often used to indicate that a variable doesn’t have any meaningful data yet. It’s an object of its own
datatype — NoneType.

None is not the same as 0, False, or an empty string.

It’s used in comparisons, default arguments, and when checking if a variable was assigned any value or not.

84. What is a recursive lambda function?

A recursive lambda is a lambda function that calls itself to solve problems. However, since lambda functions in
Python are anonymous and can’t directly refer to themselves, we must assign them to a variable.

Page 49 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

85. What is a ternary operator in Python?

The ternary operator in Python is a way to write simple if-else statements in one line. It’s also called a
conditional expression.

Syntax:

x = value_if_true if condition else value_if_false

It makes code more concise and readable for small decisions. But avoid using it for complex logic, as it can
reduce readability. It’s commonly used when assigning values based on a quick condition.

86. What are Python assertions?


Assertions are a debugging tool used to test if a condition is true. If the condition is false, the program will raise
an AssertionError. They help catch bugs early by checking if your assumptions in the code hold true.

If x is less than or equal to 0, the assertion will fail. You can provide a custom error message after the comma.

Assertions are mostly used in development and testing phases. In production, they can be disabled with the -O
(optimize) switch. They are not a replacement for proper error handling but are very useful in spotting bugs
quickly.

87. What is the use of zip() in Python?

The zip() function in Python is used to combine two or more iterables (like lists or tuples) into a single iterable of
tuples. It pairs the elements from each iterable based on their position (index). If the iterables are of different
lengths, zip() stops at the shortest one.

You can use zip() for many tasks like combining data, iterating over multiple sequences at once, or transposing
rows and columns in matrices. It's efficient and easy to use, often seen in data processing, file merging, or
where multiple iterables need to be processed in parallel.

Page 50 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

88. What is the purpose of dir() in Python?

The dir() function is a built-in utility that returns a list of all attributes and methods (including inherited ones)
available for a given object. It’s widely used for introspection, helping developers understand what functionality
is available on an object without reading the source code or documentation.

When called with no arguments, dir() returns the list of names in the current local scope.

This tool is especially useful in REPL environments or debugging sessions, helping you explore objects
dynamically and understand the Python object model better.

89. What is the map() function in Python?


The map() function applies a given function to all items in an iterable and returns a map object (which is an
iterator). It’s a clean way to apply transformations to a list or tuple without writing a loop.

Syntax:

map(function, iterable)

map() is often used when you need to apply the same function to every element. It's efficient and can be
combined with other functional programming tools like filter() or reduce(). It keeps code short and readable.

90. What is the filter() function in Python?

The filter() function is used to filter elements from an iterable based on a condition.

It returns an iterator containing only the elements for which the function returns True.

Syntax:

filter(function, iterable)

It is useful when you want to keep elements that meet certain criteria and discard the rest. filter() makes your
code more expressive and avoids manual loops with conditional checks
Page 51 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

91. What is the reduce() function in Python?

The reduce() function from the functools module applies a function to the items of a sequence and reduces it
to a single value.

It processes the sequence pairwise.

Syntax:

from functools import reduce

reduce(function, iterable)

You can use reduce() for operations like summing, multiplying, or combining values. It's powerful, but
sometimes less readable than a loop or sum(). Use it when you need to process a list into a single result step by
step.

92. What is a frozenset in Python?

A frozenset is the immutable version of a Python set. It cannot be modified after creation, which means you
cannot add or remove elements. This immutability makes it hashable, allowing it to be used as a key in
dictionaries or as elements in other sets.

It supports all set operations like union, intersection, and difference. Use frozenset when you need to ensure
the contents of a set do not change, especially when dealing with caching, memoization, or set-based keys.

93. What is the difference between yield and return in Python?

Both yield and return are used in functions, but they work very differently. return ends a function and sends
back a value. Once return is called, the function ends. On the other hand, yield pauses the function and sends
a value but keeps the function state alive for the next call.

With yield, the function becomes a generator. You can use next() to get the next value from it.

Page 52 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

94. What is the with statement in Python and why is it used?

The with statement in Python is used for resource management, such as working with files or network
connections. It ensures that resources are properly closed after they are used, even if an error occurs during
their use.

Here, file is automatically closed when the block ends. This is better than manually calling file.close() because
it handles exceptions safely.

The with statement works with context managers, which define __enter__() and __exit__() methods. It makes
your code cleaner, safer, and easier to maintain.

Note: file.txt uploaded in course resource section.

95.Write a Python program to do arithmetical operations addition and division.

Page 53 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

96.Write a Python program to find the area of a triangle.

97.Write a Python program to swap two variables.

Page 54 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

98.Write a Python program to generate a random number.

99.Write a Python program to convert kilometers to miles.

100.Write a Python program to convert Celsius to Fahrenheit.

101.Write a Python program to display calendar.

Page 55 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

102.Write a Python program to solve quadratic equation.

The standard form of a quadratic equation is:

where

a, b and c are real numbers and

The solutions of this quadratic equation is given by:

ax + bx + c = 0

a≠0

(−b ± (b − 4ac )/(2a)

Page 56 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

103.Write a Python program to swap two variables without temp variable.

104.Write a Python Program to Check if a Number is Positive, Negative or Zero.

105.Write a Python Program to Check if a Number is Odd or Even.

Page 57 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

106.Write a Python Program to Check Leap Year.

107.Write a Python Program to Check Prime Number.

A prime number is a whole number that cannot be evenly divided by any other number

except for 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers because they

cannot be divided by any other positive integer except for 1 and their own value.

Page 58 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

108.Write a Python Program to Print all Prime Numbers in an Interval of 1-10.

109.Write a Python Program to Find the Factorial of a Number.

Example Output:

Page 59 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

110.Write a Python Program to Display the multiplication Table.

111.Write a Python Program to Print the Fibonacci sequence.

Example Output:

Page 60 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

112.Write a Python Program to Check Armstrong Number?

An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the
number of digits.

Example: 153 → 1^3 + 5^3 + 3^3 =153

Example Output:

Page 61 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

113.Write a Python Program to Find Armstrong Number in an Interval.

114.Write a Python Program to Find the Sum of Natural Numbers.

Natural numbers are a set of positive integers that are used to count and order objects.

They are the numbers that typically start from 1 and continue indefinitely, including all the

whole numbers greater than 0. In mathematical notation, the set of natural numbers is often

denoted as "N" and can be expressed as:

N = 1, 2, 3, 4, 5, 6, 7, 8, . . .

Page 62 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

115.Write a Python Program to Find LCM.

Least Common Multiple (LCM):

LCM, or Least Common Multiple, is the smallest multiple that is exactly divisible by two or

more numbers.

Formula:

For two numbers a and b, the LCM can be found using the formula:

For more than two numbers, you can find the LCM step by step, taking the LCM of pairs of

numbers at a time until you reach the last pair.

Note: GCD stands for Greatest Common Divisor.

116.Write a Python Program to Find HCF.

Highest Common Factor(HCF):

HCF, or Highest Common Factor, is the largest positive integer that divides two or more

numbers without leaving a remainder.

For two numbers a and b, the HCF can be found using the formula:

HCF(a, b) = GCD(a, b)

For more than two numbers, you can find the HCF by taking the GCD of pairs of numbers at

a time until you reach the last pair.

Note: GCD stands for Greatest Common Divisor.


Page 63 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

117.Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal?

Example Output:

Page 64 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

118.Write a Python Program To Find ASCII value of a character.

ASCII value:

ASCII, or American Standard Code for Information Interchange, is a character encoding

standard that uses numeric values to represent characters. Each ASCII character is

assigned a unique 7-bit or 8-bit binary number, allowing computers to exchange information

and display text in a consistent way. The ASCII values range from 0 to 127 (for 7-bit ASCII)

or 0 to 255 (for 8-bit ASCII), with each value corresponding to a specific character, such as

letters, digits, punctuation marks, and control characters.

119.Write a Python Program to Display Fibonacci Sequence Using Recursion.

Page 65 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

120.Write a Python Program to Find Factorial of Number Using Recursion.

The factorial of a non-negative integer ( n ) is the product of all positive integers less than or

equal to ( n ). It is denoted by ( n! ) and is defined as:

n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

0! is defined to be 1.

Factorials are commonly used in mathematics, especially in combinatorics and probability,

to count the number of ways a set of elements can be arranged or selected.

121.Write a Python Program to calculate the natural logarithm of any number.

Page 66 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

122.Write a Python Program for cube sum of first n natural numbers?

Example Output:

Without Formula – using loop:

Page 67 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

123.Write a Python Program to find sum of array.

two simple methods: using a loop and using Python's built-in sum() function.

Output:

Page 68 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

124.Write a Python Program to find largest element in an array.

125.Write a Python Program for array rotation.

Left Rotate an Array in Python

Output:

Page 69 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

126.Write a Python Program to Split the array and add the first part to the end?

127.Write a Python Program to check if given array is Monotonic.

Page 70 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

128.Write a Python Program to Transpose a Matrix.

129.Write a Python Program to Sort Words in Alphabetic Order.

Page 71 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

130.Write a Python Program to Remove Punctuation From a String.

131.Write a Python program to check if the given number is a Disarium Number.

A Disarium number is a number that is equal to the sum of its digits each raised to the

power of its respective position.

For example, 89 is a Disarium number because

8 + = 8 + 81 = 89.

Page 72 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

132.Write a Python program to print all disarium numbers between 1 to 100.

133.Write a Python program to check if the given number is Happy Number.

Happy Number: A Happy Number is a positive integer that, when you repeatedly replace

the number by the sum of the squares of its digits and continue the process, eventually

reaches 1. If the process never reaches 1 but instead loops endlessly in a cycle, the number

is not a Happy Number.

Page 73 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

134.Write a Python program to print all happy numbers between 1 and 100.

135.Write a Python program to determine whether the given number is a Harshad Number.

A Harshad number (or Niven number) is an integer that is divisible by the sum of its digits.

In other words, a number is considered a Harshad number if it can be evenly divided by the

sum of its own digits.

Page 74 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

136.Write a Python program to print all pronic numbers between 1 and 100.

A pronic number, also known as an oblong number or rectangular number, is a type of

figurate number that represents a rectangle. It is the product of two consecutive integers, n

and (n + 1). Mathematically, a pronic number can be expressed as:

For example, the first few pronic numbers are:

P = n ∗ (n + 1) n

P1 = 1 ∗ (1 + 1) = 2

P2 = 2 ∗ (2 + 1) = 6

P3 = 3 ∗ (3 + 1) = 12

P4 = 4 ∗ (4 + 1) = 20

137.Write a Python program to find sum of elements in list.

Page 75 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

138.Write a Python program to Multiply all numbers in the list.

139.Write a Python program to find smallest number in a list.

140.Write a Python program to find largest number in a list.

Output:

Page 76 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

141.Write a Python program to find second largest number in a list.

142.Write a Python program to find N largest elements from a list.

143.Write a Python program to print even numbers in a list.

Page 77 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

144.Write a Python program to print odd numbers in a List.

145.Write a Python program to Remove empty List from List.

146.Write a Python program to Cloning or Copying a list.

Page 78 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

147.Write a Python program to Count occurrences of an element in a list.

148.Write a Python program to find words which are greater than given length k.

Page 79 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

149.Write a Python program for removing i th character from a string.

150.Write a Python program to split and join a string.

Page 80 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

151.Write a Python program to check if a given string is binary string or not.

152.Write a Python program to find uncommon words from two Strings.

Page 81 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

153.Write a Python program to find all duplicate characters in string.

154.Write a Python Program to check if a string contains any special character.

Use Regular Expressions (re module)

Page 82 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Output:

155.Write a Python program to Extract Unique dictionary values.

Page 83 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

156.Write a Python program to find the sum of all items in a dictionary.

157.Write a Python program to Merging two Dictionaries.

Page 84 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

158.Write a Python program to convert key-values list to flat dictionary.

159.Write a Python program to insertion at the beginning in OrderedDict.

160.Write a Python program to sort Python Dictionaries by Key or Value

Page 85 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

161.Write a program that accepts a sentence and calculate the number of letters and digits.

Suppose the following input is supplied to the program:

hello world! 123

Then, the output should be:

LETTERS 10

DIGITS 3

Page 86 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

162.Define a class with a generator which can iterate the numbers, which are divisible by 7, between a
given range 0 and n.

163.Define a class Person and its two child classes: Male and Female. All classes have a method
"getGender" which can print "Male" for Male class and "Female" for Female class.

Page 87 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

164.Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play",
"Love"] and the object is in ["Hockey","Football"].

165.Please write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list.

Page 88 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

166.Please write a program using generator to print the numbers which can be divisible by 5 and 7
between 0 and n in comma separated form while n is input by console.
Example:

If the following n is given as input to the program:

100

Then, the output of the program should be:

0,35,70

167.Please write a program using generator to print the even numbers between 0 and n in comma
separated form while n is input by console.
Example:

If the following n is given as input to the program:

10

Then, the output of the program should be:

0,2,4,6,8,10

Page 89 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

168.Please write a program using list comprehension to print the Fibonacci Sequence in comma
separated form with a given n input by console.

Output:

169.please write program to print the user name of a given email address. Both user names and company
names are composed of letters only.

Assuming that we have some email addresses in the


"username@companyname.com (mailto:username@companyname.com)" format

Page 90 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

170. Create a class called Shape with a method area() that returns 0. Then, create a subclass called
Square that takes the side length as input and overrides the area() method to return the area of the
square.

171.The "Reverser" takes a string as input and returns that string in reverse order, with the opposite case.

Examples

reverse("Hello World") ➞ "DLROw OLLEh"

reverse("ReVeRsE") ➞ "eSrEvEr"

reverse("Radar") ➞ "RADAr"

Page 91 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

172.Write a function that calculates the factorial of a number recursively.

Examples

factorial(5) ➞ 120

factorial(3) ➞ 6

factorial(1) ➞ 1

factorial(0) ➞ 1

173.Create a function that takes a string and returns a string in which each character is repeated once.

Examples

double_char("String") ➞ "SSttrriinngg"

double_char("Hello World!") ➞ "HHeelllloo WWoorrlldd!!"

double char("1234! ") ➞ "11223344!! "

Page 92 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

174.Create a function that reverses a boolean value and returns the string "boolean expected" if another
variable type is given.

Examples

reverse(True) ➞ False

reverse(False) ➞ True

reverse(0) ➞ "boolean expected"

reverse(None) ➞ "boolean expected"

175.Create a function that returns the thickness (in meters) of a piece of paper after folding it n number of
times. The paper starts off with a thickness of 0.5mm.

Examples

num_layers(1) ➞ "0.001m"

- Paper folded once is 1mm (equal to 0.001m)

num_layers(4) ➞ "0.008m"

- Paper folded 4 times is 8mm (equal to 0.008m)

num_layers(21) ➞ "1048.576m"

- Paper folded 21 times is 1048576mm (equal to 1048.576m)

Page 93 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

176.Create a function that takes a single string as argument and returns an ordered list containing the
indices of all capital letters in the string.

index_of_caps("eDaBiT") ➞ [1, 3, 5]

index_of_caps("eQuINoX") ➞ [1, 3, 4, 6]

index_of_caps("determine") ➞ []

index_of_caps("STRIKE") ➞ [0, 1, 2, 3, 4, 5]

index_of_caps("sUn") ➞ [1]

Page 94 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

177.Using list comprehensions, create a function that finds all even numbers from 1 to the given number.

Examples

find_even_nums(8) ➞ [2, 4, 6, 8]

find_even_nums(4) ➞ [2, 4]

find_even_nums(2) ➞ [2]

178.Create a function that takes a list of strings and integers, and filters out the list so that it returns a list
of integers only.

Examples:

filter_list([1, 2, 3, "a", "b", 4]) ➞ [1, 2, 3, 4]


filter_list(["A", 0, "Edabit", 1729, "Python", 1729]) ➞ [0, 1729]
filter_list(["Nothing", "here"]) ➞ []

Page 95 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

179.Given a list of numbers, create a function which returns the list but with each element's index in the
list added to itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc...

Examples:

add_indexes([0, 0, 0, 0, 0]) ➞ [0, 1, 2, 3, 4]

add_indexes([1, 2, 3, 4, 5]) ➞ [1, 3, 5, 7, 9]

add_indexes([5, 4, 3, 2, 1]) ➞ [5, 5, 5, 5, 5]

180.Create a function that takes the height and radius of a cone as arguments and returns the volume of
the cone rounded to the nearest hundredth. See the resources tab for the formula.

Examples

cone_volume(3, 2) ➞ 12.57
cone_volume(15, 6) ➞ 565.49
cone_volume(18, 0) ➞ 0

Page 96 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

181.Create a function that takes a list of numbers between 1 and 10 (excluding one number) and returns
the missing number.

Examples

missing_num([1, 2, 3, 4, 6, 7, 8, 9, 10]) ➞ 5
missing_num([7, 2, 3, 6, 5, 9, 1, 4, 8]) ➞ 10
missing_num([10, 5, 1, 2, 4, 6, 8, 3, 9]) ➞ 7

182.Write a function that takes a list and a number as arguments. Add the number to the end of the list,
then remove the first element of the list. The function should then return the updated list.

Examples

next_in_line([5, 6, 7, 8, 9], 1) ➞ [6, 7, 8, 9, 1]


next_in_line([7, 6, 3, 23, 17], 10) ➞ [6, 3, 23, 17, 10]
next_in_line([1, 10, 20, 42 ], 6) ➞ [10, 20, 42, 6]
next_in_line([], 6) ➞ "No list has been selected"

Page 97 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

183.Create the function that takes a list of dictionaries and returns the sum of people's budgets.

Examples

get_budgets([

{ 'name': 'John', 'age': 21, 'budget': 23000 },


{ 'name': 'Steve', 'age': 32, 'budget': 40000 },
{ 'name': 'Martin', 'age': 16, 'budget': 2700 }
]) ➞ 65700
get_budgets([

{ 'name': 'John', 'age': 21, 'budget': 29000 },


{ 'name': 'Steve', 'age': 32, 'budget': 32000 },
{ 'name': 'Martin', 'age': 16, 'budget': 1600 }
]) ➞ 62600

Page 98 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

185.Create a function that takes a string and returns a string with its letters in alphabetical order.

Examples

alphabet_soup("hello") ➞ "ehllo"

alphabet_soup("edabit") ➞ "abdeit"

alphabet_soup("hacker") ➞ "acehkr"

alphabet_soup("geek") ➞ "eegk"

alphabet_soup("javascript") ➞ "aacijprstv"

186.Write a function that takes a list of elements and returns only the integers.

Examples

return_only_integer([9, 2, "space", "car", "lion", 16]) ➞ [9, 2, 16]

return_only_integer(["hello", 81, "basketball", 123, "fox"]) ➞ [81, 123]

return_only_integer([10, "121", 56, 20, "car", 3, "lion"]) ➞ [10, 56, 20,3]

return_only_integer(["String", True, 3.3, 1]) ➞ [1]

Page 99 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

187.Create a function that takes three parameters where: - x is the start of the range (inclusive). - y is the
end of the range (inclusive). - n is the divisor to be checked against. Return an ordered list with numbers
in the range that are divisible by the third parameter n. Return an empty list if there are no numbers that
are divisible by n.

Examples

list_operation(1, 10, 3) ➞ [3, 6, 9]

list_operation(7, 9, 2) ➞ [8]

list_operation(15, 20, 7) ➞ []

188.Create a function that takes in two lists and returns True if the second list follows the first list by one
element, and False otherwise. In other words, determine if the second list is the first list shifted to the
right by 1.

Examples

simon_says([1, 2], [5, 1]) ➞ True

simon_says([1, 2], [5, 5]) ➞ False

simon_says([1, 2, 3, 4, 5], [0, 1, 2, 3, 4]) ➞ True

simon_says([1, 2, 3, 4, 5], [5, 5, 1, 2, 3]) ➞ False

Notes:

- Both input lists will be of the same length, and will have a minimum length of 2.

- The values of the 0-indexed element in the second list and the n-1th indexed element in the first list do not
matter.

Page 100 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

189.A group of friends have decided to start a secret society. The name will be the first letter of each of
their names, sorted in alphabetical order. Create a function that takes in a list of names and returns the
name of the secret society.

Examples

society_name(["Adam", "Sarah", "Malcolm"]) ➞ "AMS"


society_name(["Harry", "Newt", "Luna", "Cho"]) ➞ "CHLN"
society_name(["Phoebe", "Chandler", "Rachel", "Ross", "Monica", "Joey"])

Page 101 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

190.Create a function that takes a string and returns True or False, depending on whether the characters
are in order or not.
Examples

is_in_order("abc") ➞ True
is_in_order("edabit") ➞ False
is_in_order("123") ➞ True
is_in_order("xyzz") ➞ True

191.Create a function that squares every digit of a number.

Examples

square_digits(9119) ➞ 811181
square_digits(2483) ➞ 416649
square_digits(3212) ➞ 9414

Notes

The function receives an integer and must return an integer.

Page 102 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

192.Create a function that sorts a list and removes all duplicate items from it.

Examples

setify([1, 3, 3, 5, 5]) ➞ [1, 3, 5]


setify([4, 4, 4, 4]) ➞ [4]
setify([5, 7, 8, 9, 10, 15]) ➞ [5, 7, 8, 9, 10, 15]
setify([3, 3, 3, 2, 1]) ➞ [1, 2, 3]

193.Create a function that returns the mean of all digits.

Examples
mean(42) ➞ 3
mean(12345) ➞ 3
mean(666) ➞ 6

Notes
The mean of all digits is the sum of digits / how many digits there are (e.g. mean
of digits in 512 is (5+1+2)/3(number of digits) = 8/3=2).
The mean will always be an integer.

Page 103 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

194.Write a function that creates a dictionary with each (key, value) pair being the (lower case, upper
case) versions of a letter, respectively.

Examples

mapping(["p", "s"]) ➞ { "p": "P", "s": "S" }


mapping(["a", "b", "c"]) ➞ { "a": "A", "b": "B", "c": "C" }
mapping(["a", "v", "y", "z"]) ➞ { "a": "A", "v": "V", "y": "Y", "z": "Z" }

Notes
All of the letters in the input list will always be lowercase.

195.Write a function that converts a dictionary into a list of keys-values tuples.

Examples

dict_to_list({
"D": 1,
"B": 2
"C": 3
}) ➞ [("B", 2), ("C", 3), ("D", 1)]
dict_to_list({
"likes": 2,
"dislikes": 3,
"followers": 10
}) ➞ [("dislikes", 3), ("followers", 10), ("likes", 2)]

Notes
Return the elements in the list in alphabetical order.

Page 104 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

196.Create a function that takes three integer arguments (a, b, c) and returns the amount of integers
which are of equal value.

Examples

equal(3, 4, 3) ➞ 2
equal(1, 1, 1) ➞ 3
equal(3, 4, 1) ➞ 0
Notes

Your function must return 0, 2 or 3.

Page 105 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

197.Create a function that takes a list of strings and return a list, sorted from shortest to longest.

Examples

sort_by_length(["Google", "Apple", "Microsoft"]) ➞ ["Apple", "Google", "Microsoft"]


sort_by_length(["Leonardo", "Michelangelo", "Raphael", "Donatello"]) ➞ ["Raphael",
"Leonardo", "Donatello", "Michelangelo"]
sort_by_length(["Turing", "Einstein", "Jung"]) ➞ ["Jung", "Turing", "Einstein"]

All test cases contain lists with strings of different lengths, so you won't have to deal

198.Create a function that takes a list of numbers and return the number that's unique.

Examples

unique([3, 3, 3, 7, 3, 3]) ➞ 7
unique([0, 0, 0.77, 0, 0]) ➞ 0.77
unique([0, 1, 1, 1, 1, 1, 1, 1]) ➞ 0
Notes

Test cases will always have exactly one unique number while all others are the same.

Page 106 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

199.You are given two strings word1 and word2. Merge the strings by adding letters in alternating order,
starting with word1. If a string is longer than the other, append the additional letters onto the end of the
merged string.

Example 1:

Input: word1 = "abc", word2 = "pqr"


Output: "apbqcr"

Page 107 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

200.For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e, t is concatenated
with itself one or more times). Given two strings str1 and str2, return the largest string x such that x
divides both str1 and str2
Example 1:

Input: str1 = "ABCABC", str2 = "ABC"


Output: "ABC"

201. You have a list of kids, and each kid has a certain number of candies. You're also given some extra
candies. For each kid, check: If we give all the extra candies to that kid, will they have the most candies
(or equal to the most) compared to the others? Return a list of True or False for each kid.

Page 108 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Explanation:

• Max candies any kid has = 5


• Give 3 extra candies to each kid and see if their total becomes ≥ 5
• Result: [True, True, True, False, True]

202.You have a long flowerbed in which some of the plots are planted, and some are not. However,
flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an
integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers
rule and false otherwise

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1

Output: true

Page 109 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

203.Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and
'u', and they can appear in both lower and upper cases, more than once.

204.Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one
space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string
should only have a single space separating the words. Do not include any extra spaces.

Page 110 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

205.Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the
non-zero elements.

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]

206.Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a
string is a new string that is formed from the original string by deleting some (can be none) of the
characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a
subsequence of "abcde" while "aec" is not).

Page 111 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

207.You are given an integer array nums and an integer k. In one operation, you can pick two numbers
from the array whose sum equals k and remove them from the array. Return the maximum number of
operations you can perform on the array.

208.You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous
subarray whose length is equal to k that has the maximum average value and return this value. Any
answer with a calculation error less than 10-5 will be accepted.

Page 112 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

209.Given a string s and an integer k, return the maximum number of vowel letters in any substring of s
with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

210.Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the
array if you can flip at most k 0's.

Page 113 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

211.Given a binary array nums, you should delete one element from it. Return the size of the longest non-
empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

212.There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The
biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where
gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a
point.

Page 114 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

213.Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index
where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers
strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there
are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index.
If no such index exists, return -1.

214.Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: answer[0]
is a list of all distinct integers in nums1 which are not present in nums2. answer[1] is a list of all distinct
integers in nums2 which are not present in nums1. Note that the integers in the lists may be returned in
any order.

Page 115 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

215.Given an array of integers arr, return true if the number of occurrences of each value in the array is
unique or false otherwise.

216.You are given a string s, which contains stars *. In one operation, you can: Choose a star in s. Remove
the closest non-star character to its left, as well as remove the star itself. Return the string after all stars
have been removed.

217.A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing
all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters
include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise.

Page 116 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

218.Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

219.Given a string s consisting of words and spaces, return the length of the last word in the string. A word
is a maximal substring consisting of non-space characters only.

220.Write a function to find the longest common prefix string amongst an array of strings

Page 117 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

221.How do you count the number of 1s and 0s in a Python list?

Input
a = [1, 1, 0, 0, 1, 1, 0, 1]

Answer:

a = [1, 1, 0, 0, 1, 1, 0, 1]
c1 = c2 = 0

for i in a:
if i == 1:
c1 += 1
elif i == 0:
c2 += 1

print("Count of 1s:", c1)


print("Count of 0s:", c2)

Output:

Count of 1s: 5
Count of 0s: 3

Explanation
• The list a contains binary values (0s and 1s).
• The loop checks each element:
o If it is 1, it increments c1.
o If it is 0, it increments c2.
• Final values of c1 and c2 represent the count of 1s and 0s, respectively.

222. Write a Python program to print all numbers that occur more than once in the list.

numbers = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 4, 5]

Answer:

from collections import Counter

numbers = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 4, 5]

# Count frequency of each number


freq = Counter(numbers)

# Print numbers that appear more than once


repeated = [num for num, count in freq.items() if count > 1]
print("Repeated numbers:", repeated)

Output:

Repeated numbers: [4, 5, 7, 9]


Page 118 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

223. Write a Python class named person with attributes name and age. Create an object of this class with
name "john" and age 25, and print the name of the person.

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

p1 = person("john", 25)
print(p1.name)

Output: john

Explanation:
• A class person is defined with an __init__ constructor.
• When p1 = person("john", 25) is executed:
o p1.name is set to "john"
o p1.age is set to 25
• print(p1.name) prints the value of the name attribute: john

224.Write a Python program to extract all consecutive digits from a string and calculate their total sum.

Input String:

s = "23jkhbpj234bi[h32b42i[h3b4h[2b3[4ih"

Answer:

import re

s = "23jkhbpj234bi[h32b42i[h3b4h[2b3[4ih"

# Extract all consecutive digits as integers


numbers = re.findall(r'\d+', s)

# Convert to int and calculate sum


total = sum(map(int, numbers))

print("Extracted numbers:", numbers)


print("Sum:", total)

Output:

Extracted numbers: ['23', '234', '32', '42', '3', '4', '2', '3', '4']
Sum: 347

Explanation:
• Use the re.findall(r'\d+', s) function to extract all consecutive digits (numbers like '23', '234', etc.).
• Convert the list of strings to integers using map(int, ...).
• Calculate the sum using sum(...).

Page 119 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

225.Please write a program to randomly print a integer number between 7 and 15 inclusive.

226.Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 ,
between 1 and 1000 inclusive.

227.Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10
inclusive using random module and list comprehension.

228.Please generate a random float where the value is between 5 and 95 using Python math module.

Page 120 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

229.Please write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list

230.Please write a program which accepts basic mathematic expression from console and print the
evaluation result.

Example: If the following string is given as input to the program:

35+3

Then, the output of the program should be:

38

Page 121 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

231.Please write assert statements to verify that every number in the list [2,4,6,8] is even.

232.Please write a program using generator to print the numbers which can be divisible by 5 and 7
between 0 and n in comma separated form while n is input by console.

Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70

233.Define a custom exception class which takes a string message as attribute.

Page 122 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

234.Define a class named Shape and its subclass Square. The Square class has an init function which
takes a length as argument. Both classes have a area function which can print the area of the shape
where Shape's area is 0 by default.

235.Define a class named Rectangle which can be constructed by a length and width. The Rectangle
class has a method which can compute the area.

236.Define a class named Circle which can be constructed by a radius. The Circle class has a method
which can compute the area.

Page 123 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

237.Write a program which can map() to make a list whose elements are square of numbers between 1
and 20 (both included).

238.Write a program to generate and print another tuple whose values are even numbers in the given
tuple (1,2,3,4,5,6,7,8,9,10).

239. How does Python handle memory management?.

Python uses:
• Automatic garbage collection (via the gc module),
• Reference counting to keep track of objects,
• Memory pools (via PyMalloc) for efficient allocation of small objects.
This ensures unused memory is freed and reused.

240. What is the difference between a list and a generator in Python?

• List stores all elements in memory at once.


• Generator computes values on the fly, using yield, which is memory-efficient.

Page 124 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

241. How can you handle missing values in a dataset using Python?

242. What are Python generators? How are they different from regular functions?

A generator is a special type of function that returns an iterator, but instead of returning all values at once, it
yields one value at a time, on demand.

Key Differences:

Feature Regular Function (return) Generator (yield)


Returns A single value or object An iterator (one item at a time)
Memory Efficiency Loads all values into memory Lazy evaluation (saves memory)
Syntax Uses return Uses yield

Example:

Use Case in Data Engineering:

• Ideal for processing large files, streaming data, or batch ETL operations where loading everything in
memory is not feasible.

Page 125 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Website:

Website: https://www.cleverstudies.com/

Email: cleverstudies.edu@gmail.com , support@cleverstudies.com

Youtube: https://www.youtube.com/@cleverstudies

Topmate:

Connect with me one to one: https://topmate.io/naresh_kumar_boddupally

LinkedIn

Clever Studies LinkedIn: Naresh Kumar Boddupally | LinkedIn

WhatsApp:

Clever Studies 2.0 (950 Members): https://chat.whatsapp.com/BXyqRBHsXcrAPH2Y6505ZE

Clever Studies (1025 Members): https://chat.whatsapp.com/C70cGzAEKC1LnSw60U9FVO

Clever Studies Premium: Only for enrolled members

Telegram:

Clever Studies Official Telegram Group (875 Members): https://t.me/+eMaiZNWTPmZkYmVl

Page 126 of 127


PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]

Thank You!

Page 127 of 127

You might also like