Python Q&A for Data Engineers
Python Q&A for Data Engineers
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]
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]
Page 5 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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. 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!")
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]
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
Example:
Page 11 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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
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.
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]
Example:
For multi-line comments, you can use # on each line or use triple quotes (''' or """) as a workaround:
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++
Page 14 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
The key difference between a function and a method in Python lies in how they are defined and used:
Function
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:
Page 15 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
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:
Conditional statements are used to run certain blocks of code only when specific conditions are met.
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?
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]
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]
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:
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:
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]
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.
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.
Syntax of a Decorator
Page 22 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
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]
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.
Page 24 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Summary:
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.
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:
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]
A decorator in Python is a function that takes another function as input and adds extra functionality to it,
without changing its original structure.
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.
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]
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.
In Python, *args and **kwargs are used in function definitions to allow the function to accept a variable number
of arguments.
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]
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.
Python provides built-in functions to perform file operations such as reading, writing, and appending. The core
function used is open().
Basic Syntax:
Page 30 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Using with automatically closes the file even if an error occurs — it's the recommended way.
Tips:
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]
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.
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.
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:
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.
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]
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.
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]
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.
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]
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].
Slicing is powerful for reversing sequences, picking even-indexed items, or extracting parts of text. It works with
strings to
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]
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.
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.
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]
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).
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.
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]
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.
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?
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.
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.
Page 41 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
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]
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:
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
Page 43 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
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().
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]
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.
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
73.Please write a program which count and print the numbers of each character in a string input by
console.
abcdefgabc
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].
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]
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.
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.
It’s used in comparisons, default arguments, and when checking if a variable was assigned any value or not.
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]
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:
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.
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.
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]
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.
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.
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]
The reduce() function from the functools module applies a function to the items of a sequence and reduces it
to a single value.
Syntax:
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.
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.
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]
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.
Page 53 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 54 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 55 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
where
ax + bx + c = 0
a≠0
Page 56 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 57 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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]
Example Output:
Page 59 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Example Output:
Page 60 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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 Output:
Page 61 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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
N = 1, 2, 3, 4, 5, 6, 7, 8, . . .
Page 62 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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
HCF, or Highest Common Factor, is the largest positive integer that divides two or more
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
Example Output:
Page 64 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
ASCII value:
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
Page 65 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
The factorial of a non-negative integer ( n ) is the product of all positive integers less than or
n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
0! is defined to be 1.
Page 66 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Example Output:
Page 67 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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]
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?
Page 70 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 71 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
A Disarium number is a number that is equal to the sum of its digits each raised to the
8 + = 8 + 81 = 89.
Page 72 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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
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
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.
figurate number that represents a rectangle. It is the product of two consecutive integers, n
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
Page 75 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Output:
Page 76 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 77 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 78 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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]
Page 80 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 81 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 82 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Output:
Page 83 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
Page 84 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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.
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:
100
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:
10
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.
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("ReVeRsE") ➞ "eSrEvEr"
reverse("Radar") ➞ "RADAr"
Page 91 of 127
PYTHON INTERVIEW QUESTIONS & ANSWERS FOR DATA ENGINEERS [WWW.CLEVERSTUDIES.COM]
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"
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
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"
num_layers(4) ➞ "0.008m"
num_layers(21) ➞ "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:
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:
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
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([
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
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(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
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.
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
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
Examples
square_digits(9119) ➞ 811181
square_digits(2483) ➞ 416649
square_digits(3212) ➞ 9414
Notes
192.Create a function that sorts a list and removes all duplicate items from it.
Examples
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.
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
Notes
All of the letters in the input list will always be lowercase.
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.
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
197.Create a function that takes a list of strings and return a list, sorted from shortest to longest.
Examples
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.
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:
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:
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.
Explanation:
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:
Output: true
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.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one
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.
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.
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).
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.
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.
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.
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.
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.
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
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
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:
numbers = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 4, 5]
Output:
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"
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(...).
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.
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.
35+3
38
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
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.
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).
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.
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:
Example:
• Ideal for processing large files, streaming data, or batch ETL operations where loading everything in
memory is not feasible.
Website:
Website: https://www.cleverstudies.com/
Youtube: https://www.youtube.com/@cleverstudies
Topmate:
WhatsApp:
Telegram:
Thank You!