Python Interview Questions and Answers For 2024
Python Interview Questions and Answers For 2024
edurek
We have compiled a list of top Python interview questions which are classi�ed into 7 sections, na
• Basic Interview Questions
• OOPS Interview Questions
• Basic Python Programs
• Python Libraries Interview Questions
• Web Scraping Interview Questions
• Data Analysis Interview Questions
• Multiple Choice Questions (MCQ)
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
• Python is an language. That means that, unlike languages like C and its varia
compiled before it is run. Other interpreted languages include PHP and Ruby.
• Python is , this means that you don’t need to state the types of varia
anything like that. You can do things like x=111 and then x="I'm a string" without error
• Python is well suited to in that it allows the de�nition o
and inheritance. Python does not have access speci�ers (like C++’s public, private).
• In Python, are . This means that they can be assigned to
functions and passed into functions. Classes are also �rst class objects
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
readability.
A namespace in python refers to the name which is assigned to each object in python. The o
functions. As each object is created, its name along with space(the address of the outer function
created. The namespaces are maintained in python like a dictionary where the key is the namesp
the object. There 4 types of namespace in python-
1. – These namespaces contain all the built-in objects in python and are a
running.
2. – These are namespaces for all the objects created at the level of the ma
3. – These namespaces are at the higher level or outer function.
4. – These namespaces are at the local or inner function.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
This ������� �������� is intended as a Crash Course on ������� for Beginners. ������� has be
exponentially. But, ������� is still not known to many people. In this video, I aim to show you th
use ������� for yourself. ������� has been the buzzword for a while now. This yap lab was put
release and has been changing the game ever since.
Dictionary and list comprehensions are just another concise way to de�ne dictionaries and
1 4
2 [0,1,2,3,4]
The .py �les are the python source code �les. While the .pyc �les contain the bytecode of th
created when the code is imported from some other source. The interpreter converts the source
by saving time. You can get a better understanding with the Data Engineering Course in Washing
Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicin
can be omitted as well. When we write [start:end] this returns all the elements of the sequence
end-1 element. If the start or end element is negative i, it means the ith element from the end. Th
how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] wil
the last element till the third element by printing every second element.i.e. [8,6,4].
Keywords in python are reserved words that have special meaning.They are generally used
Keywords cannot be used for variable or function names. There are following 33 keywords in pyt
• And
• Or
• Not
• If
• Elif
• Else
• For
• While
• Break
• As
• Def
• Lambda
• Pass
• Return
• True
• False
• Try
• With
• Assert
• Class
• Continue
• Del
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
6. Special literal- Python has 1 special literal None which is used to return a null variable.
The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1
Dataframes are joined together on a common column called a key. When we combine all the row
the join used is outer join. While, when we combine the common rows or intersection, the join us
pd.concat([dataframe1, dataframe2], axis=’axis’, join=’type_of_join)
• Deprecated functions and commands such as deprecated parser and symbol modules, dep
• Removal of erroneous methods, functions, etc.
Python modules are �les containing Python code. This code can either be functions classes
a .py �le containing executable code.
• os
• sys
• math
• random
• data time
• JSON
Variables declared outside a function or in global space are called global variables. These va
function in the program.
Any variable declared inside a function is known as a local variable. This variable is present i
global space.
1 a=2
2 def add():
3 b=3
4 c=a+b
5 print(c)
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
This function is used to convert a tuple of order (key, value) into a dictionary.
Indentation is necessary for Python. It speci�es a block of code. All code within loops, cl
within an indented block. It is usually done using four space characters. If your code is not
execute accurately and will throw errors as well.
Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a si
lists can hold any data type elements.
A function is a block of code which is executed only when it is called. To de�ne a Python fun
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
1 class Employee:
2 def __init__(self, name, age,salary):
3 self.name = name
4 self.age = age
5 self.salary = 20000
6 E1 = Employee("XYZ", 23, 20000)
7 # E1 is the instance of class Employee.
8 #__init__ allocates memory for E1.
9 print(E1.name)
10 print(E1.age)
11 print(E1.salary)
XYZ
23
20000
An anonymous function is known as a lambda function. This function can have any number
one statement.
11
Self is an instance or an object of a class. In Python, this is explicitly included as the �rst pa
case in Java where it’s optional. It helps to di�erentiate between the methods and attributes of a
The self variable in the init method refers to the newly created object while in other method
method was called.
Allows loop termination when some condition is met and the control is t
Break
to the next statement.
Used when you need some block of code syntactically, but you want
Pass
execution. This is basically a null operation. Nothing happens when this is
Random module is the standard module that is used to generate a random number. The m
1 import random
2 random.random
The statement random.random() method return the �oating-point number that is in the range
random �oat numbers. The methods that are used with the random class are the bound meth
instances of the Random can be done to show the multi-threading programs that creates a
threads. The other random generators that are used in this are:
1. : it chooses an integer and de�ne the range in-between [a, b). It retur
randomly from the range that is speci�ed. It doesn’t build a range object.
2. : it chooses a �oating point number that is de�ned in the range of [a,b).Iyt ret
3. : it is used for the normal distribution where the mu is a mea
used for standard deviation.
4. that is used and instantiated creates independent multiple random num
For the most part, xrange and range are the exact same in terms of functionality. They both
of integers for you to use, however you please. The only di�erence is that range returns a Pytho
an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It crea
with a special technique called yielding. This technique is used with a type of object known as ge
have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function
� � �
Pickle module accepts any Python object and converts it into a string representation and d
function, this process is called pickling. While the process of retrieving original
Python
representation is called unpickling.
In Python, the capitalize() method capitalizes the �rst letter of a string. If the string already
beginning, then, it returns the original string.
1 stg='ABCD'
2 print(stg.lower())
abcd
Multi-line comments appear in more than one line. All the lines to be commented are to b
very good . All you need to do is hold the ctrl
wherever you want to include a # character and type a # just once. This will comment all the
cursor.
Docstrings are not actually comments, but, they are . These doc
They are not assigned to any variable and therefore, at times, serve the purpose of comments as
1 """
2 Using docstring as a comment.
3 This code divides 2 numbers
4 """
5 x=8
6 y=4
7 z=x/y
8 print(z)
2.0
2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
3. On exit, because of having its own e�cient clean up mechanism, Python would try to de-all
The built-in datatypes in Python is called dictionary. It de�nes one-to-one relationship betw
contain pair of keys and their corresponding values. Dictionaries are indexed by keys.
The following example contains some keys. Country, Capital & PM. Their corresponding va
respectively.
1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1 print dict[Country]
Output:India
1 print dict[Capital]
Output:Delhi
1 print dict[PM]
Output:Modi
The Ternary operator is the operator that is used to show the conditional statements. T
values with a statement that has to be evaluated for it.
The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is retur
then big=y will be sent as a result.
We use *args when we aren’t sure how many arguments are going to be passed to a functio
list or tuple of arguments to a function. **kwargs is used when we don’t know how many keywo
function, or it can be used to pass the values of a dictionary as keyword arguments. The id
convention, you could also use *bob and **billy but that would not be wise.
The index for the negative number starts from ‘-1’ that represents the last index in the sequence
and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to
given as S[:-1]. The negative index is also used to show the index to represent the string in correc
To delete a �le in Python, you need to import the OS Module. After that, you need to use th
1 import os
2 os.remove("xyz.txt")
• Integers
• Floating-point
• Complex numbers
• Strings
• Boolean
• Built-in functions
1. Python’s lists are e�cient general-purpose containers. They support (fairly) e�cient ins
concatenation, and Python’s list comprehensions make them easy to construct and manipu
2. They have certain limitations: they don’t support “vectorized” operations like elementwise
the fact that they can contain objects of di�ering types mean that Python must store typ
and must execute type dispatching code when operating on each element.
3. NumPy is not just more e�cient; it is also more convenient. You get a lot of vector and m
sometimes allow one to avoid unnecessary work. And they are also e�ciently implemented
4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast
algebra, histograms, etc.
4.6
3.1
Python is an object-oriented programming language. This means that any program can be s
object model. However, Python can be treated as a procedural as well as structural language.
Check out these AI and ML courses by E & ICT Academy NIT Warangal to learn Python usage in AI
career.
Shallow copy is used when a new instance type gets created and it keeps the values that
Shallow copy is used to copy the reference pointers just like it copies the values. These referen
and the changes made in any member of the class will also a�ect the original copy of it. Shallow
the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the refe
makes the reference to an object and the new object that is pointed by some other object gets
original copy won’t a�ect any other copy that uses the object. Deep copy makes execution of th
certain copies for each object that is been called.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
1. Create a �le with any name and in any language that is supported by the compiler of yo
�le.cpp
2. Place this �le in the Modules/ directory of the distribution which is getting used.
3. Add a line in the �le Setup.local that is present in the Modules/ directory.
4. Run the �le using spam �le.o
5. After a successful run of this rebuild the interpreter by using the make command on the top
6. If the �le is changed then run rebuildMake�le by using the command as ‘make Make�le’.
Python libraries are a collection of Python packages. Some of the majorly used python libraries a
Scikit-learn and many more.
1 a="edureka python"
2 print(a.split())
[‘edureka’, ‘python’]
Modules can be imported using the keyword. You can import modules in three ways-
Next, in this Python Interview Questions blog, let’s have a look at Object Oriented Concepts in Py
Here is the list of Top 10 Trending Technologies in 2023 that will be in demand!
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
class and the class that is inherited is called a derived / child class.
They are di�erent types of inheritance supported by Python:
1 class Employee:
2 def __init__(self, name):
3 self.name = name
4 E1=Employee("abc")
5 print(E1.name)
abc
In Python, the term monkey patch only refers to dynamic modi�cations of a class or module
1 # m.py
2 class MyClass:
3 def f(self):
4 print "f()"
1 import m
2 def monkey_f(self):
3 print "monkey_f()"
4
5 m.MyClass.f = monkey_f
6 obj = m.MyClass()
7 obj.f()
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the function w
the module m.
Multiple inheritance means that a class can be derived from more than one parent classe
inheritance, unlike Java.
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
An empty class is a class that does not have any code de�ned within its block.
It can be
However, you can create objects of this class outside the class itself. IN PYTHON THE PASS c
executed. it’s a null statement.
1 class a:
2 pass
3 obj=a()
4 obj.name="xyz"
5 print("Name = ",obj.name)
Name = xyz
It returns a featureless object that is a base for all classes. Also, it does not take any parame
Next, let us have a look at some Basic Python Programs in these Python Interview Questions.
1 def bs(a):
2 # a = name of list
3 b=len(a)-1nbsp;
4 # minus 1 because we always compare 2 adjacent values
5 for x in range(b):
6 for y in range(b-x):
7 a[y]=a[y+1]
8
9 a=[32,5,3,6,7,54,87]
10 bs(a)
1 def pyfunc(r):
2 for x in range(r):
3 print(' '*(r-x-1)+'*'*(2*x+1))
4 pyfunc(9)
*
***
*****
*******
*********
***********
*************
***************
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
1 a=int(input("enter number"))
2 if a=1:
3 for x in range(2,a):
4 if(a%x)==0:
5 print("not prime")
6 break
7 else:
8 print("Prime")
9 else:
10 print("not prime")
enter number 3
Prime
1 a=input("enter sequence")
2 b=a[::-1]
3 if a==b:
4 print("palindrome")
5 else:
6 print("Not a Palindrome")
Let us �rst write a multiple line solution and then convert it to one-liner code.
Next, in this Python Interview Questions let's have a look at some Python Librarie
Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intenti
Jinja2 are two of their dependencies. This means it will have little to no dependencies on
framework light while there is a little dependency to update and fewer security bugs.
A session basically allows you to remember information from one request to another. In a �ask,
the user can look at the session contents and modify them. The user can modify the sessi
Flask.secret_key.
Django and Flask map the URL’s or addresses typed in the web browsers to functions in Pyt
Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will n
whereas Django does a lot for you wherein you would not need to do much work. Django consist
user will need to analyze whereas Flask gives the users to create their own code, therefore, maki
code. Technically both are equally good and both contain their own pros and cons.
• Flask is a “microframework” primarily build for a small application with simpler requirem
external libraries. Flask is ready to use.
• Pyramid is built for larger applications. It provides �exibility and lets the developer use the
developer can choose the database, URL structure, templating style and more. Pyramid is h
• Django can also be used for larger applications just like Pyramid. It includes an ORM.
Django uses SQLite as a default database, it stores data as a single �le in the �lesystem. If
—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your d
create a new database for your Django project. Either way, with your (empty) database in place,
how to use it. This is where your project’s settings.py �le comes in.
1 DATABASES = {
2 'default': {
3 'ENGINE' : 'django.db.backends.sqlite3',
4 'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
5 }
6 }
The template is a simple text �le. It can create any text-based format like XML, CSV, H
variables that get replaced with values when the template is evaluated and tags (% tag %) that co
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
Django provides a session that lets you store and retrieve data on a per-site-visitor basis.
sending and receiving cookies, by placing a session ID cookie on the client side, and storing all th
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
1. Abstract Base Classes: This style is used when you only want parent’s class to hold inform
out for each child model.
2. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need
database table.
3. Proxy models: You can use this model, If you only want to modify the Python level behavio
the model’s �elds.
Next in this Python Interview Question blog, let’s have a look at questions related to Web Scrapin
We will use the following code to save an image locally from an URL address
1 import urllib.request
2 urllib.request.urlretrieve("URL", "local-filename.jpg")
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cac
the time for. For example, to check the Google Webcache age of edureka.co you’d use the follow
http://webcache.googleusercontent.com/search?q=cache:edureka.co
The above code will help scrap data from IMDb’s top 250 list
Top 100+ Python Interview Ques�ons and Answers For 2024 h�ps://www.edurek
We can get the indices of N maximum values in a NumPy array using the below code:
1 import numpy as np
2 arr = np.array([1, 3, 2, 4, 5])
3 print(arr.argsort()[-3:][::-1])
Output
[ 4 3 1 ]
1 import numpy as np
2 a = np.array([1,2,3,4,5])
3 p = np.percentile(a, 50) #Returns 50th percentile, e.g. median
4 print(p)
:3
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in t
integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, where
of high-quality 3D visualization features, utilizing the powerful VTK engine.
Next in this Python Interview Questions blog, let’s have a look at some MCQs
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)
b, c & d.
As Python has no concept of private variables, leading underscores are used to indicate variables
outside the class.
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
b) a b c = 1000 2000 3000
1 try:
2 if '1' != 1:
3 raise "someError"
4 else:
5 print("someError has not occured")
6 except "someError":
7 print ("someError has occured")
A new exception class must inherit from a BaseException. There is no such inheritance here.
a) Error
b) None
c) 25
d) 2
c) 25
The WITH statement when used with open �le guarantees that the �le object is closed when the
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs into except block
c) when no exception occurs
I hope this set of Python Interview Questions will help you in preparing for your interviews. All th
Got a question for us? Please mention it in the comments section and we will get back to you at t
Edureka o�ers a Data Science with Python Course that will help you master the art of analyt
employing Python. You will use libraries like Pandas, Numpy, Matplotlib, Scipy, Scikit, and Pyspa
Python machine learning, scripts, sequence, web scraping, and big data analytics leveraging Apac