Python is one of the best in-demand programming languages. If you hone good Python programming skills, there are tones of job opportunities.
There are a lot of techies learning Python to get into the IT industry. There are also many who are already working and want to switch in the Python domain.
No doubt, the future is with Python.
You can use Python for web development, data analytics, data science, machine learning, artificial intelligence, automation testing, and whatnot.
If you are looking for any job opportunities in these fields, you should be good at Python programming concepts.
Dwelling into Python for many years and analyzing the trends in thus domain very closely; I’m writing this post to share with you all the interview questions which will help you throughout your career.
Going through this complete list of Python interview questions and answers, I’m sure you are pretty prepared to crack any interview.
Let’s dive in..
Table of Contents
Answer: While declaring or initializing the variable in Python programming, it is not required to mention the data type of the variable.
The Data type of the variable will be based on the type of data you assign to the variable.
Example:
Variable initialization in C programming
int var = 12;
Variable initialization in Python programming
var = 12
A variable var is an integer data type.
var = "CSEstack"
A variable var is a string data type variable
Method type() can be used to check the data type of the object.
intVar = 12
type(intVar) #int
strVar = "CSEstack"
type(strVar) #string
Depending on the data type of the variable, there are different methods associated with it.
What is Build
Everything in Python is an object. It’s correct.
What is an object?
In programming, an object is an entity that has attributes and methods associated with it.
In Python, the definition of the object is looser. Some objects may not have an argument or method, but it can be assigned to a variable or passed as an argument to other functions.
In Python, everything is considered as an object as it can fall into either one of the following.
Some of the examples of Python objects.
The functions that come predefined with the Python installation is called a built-in Python function.
You don’t need to import any of the Python libraries to use the built-in functions.
If you have Python installed on your system, you can call these built-in methods.
It is possible using the readlines()
method by importing sys
module.
Here are three lines of code for taking multi-line user input.
import sys
msg = sys.stdin.readlines()
print(msg)
For an explanation, check the tutorial.
Unlink Python list, dictionary in Python does not preserver the order of the <name, value> pairs. You can not access the elements in the Dictionary by its index.
Python 2.7 and onwards have introduced the OrderedDict
module which can found in collections.
Here is a sample code for creating an ordered dictionary which preserves the order of the pairs based on the insertion.
from collections import OrderedDict
dictEMp = OrderDict([('emp':122),('org':'Google')])
dictEmp.items()
Output:
[('emp':122),('org':'Google')]
Enumerate is very useful when it is required to loop over the list.
Python loop
listData = [4, 4, 5, 6]
for value in listData:
print(item)
Python loop using enumerate
listData = [4, 4, 5, 6]
for index, value in enumerate(listData):
print(index, ":", value)
Using enumerate with a list will give you the index and value from the list.
Class is a block of code where we write create class attributes which include class variable and class methods. Class methods that are defined by the def are also part of the class attribute.
Apart from the class variable, there is also the concept of the instance variable.
Let’s take an example:
class myClass:
def __init__(self):
self.varInst = 'This is instance variable'
varClass = 'This is a class variable.'
Here,
varInst
is an instance variable.varClass
is a class variable.When you create an instance of class myClass, a new object is created and gets initialized by calling __init__() method. This method creates one new instance (varInst) which is associated with the self keyword.
The class attribute is somewhat similar to the static variable/method which is found in many of the programming languages like C, Java…
All the objects created for the class will be using the same copy of class attributes. Whereas, there will be a separate copy of the instance variable for each instance.
It is an advanced method of creating a list. With the single line of code, you can generate the list.
Example: Write a Python program to generate a list of the first five even numbers using the list comprehension technique.
obj = [x*2 for x in range(1, 6)]
print(obj)
Output:
[2, 4, 6, 8, 10]
This is a very interesting topic. Read the list comprehension tutorial to learn in detail.
Advance Python Interview Questions
“__init__” is the reserved method in Python class. It is similar to the constructor in other programming languages. This method will be called the first time when a new object is created for that class. With __init__()
method, you can in9itiallize all the call attributes for that object.
Example:
class myClass:
def __init__(self, value):
print("Object initialization...")
self.value=value
myClass myOb
Output:
Object initialization...
The methods append() and extend() are a member function of a list object.
Example: append() in Python
listEven = [2, 4, 6]
listEven.append(10)
print(listEven)
# Output: [2, 4, 6, 10]
Example: extend() in Python
listEven = [2, 4, 6]
listEven.extend([10, 12, 14])
print(listEven)
# Output: [2, 4, 6, 10, 12, 14, 16]
Here are some of the basic differences between these two Python versions.
In Python 2, strings are stored as ASCII by default. Whereas in Python 3, test strigs are Unicode formatted by default.
When you perform mathematical operations on integers in Python 2, the result gets round up to the nearest integer value. In Python 3, you will get the exact answer in decimal points.
Python 2:
> 7/2 3
Python 3:
> 7/2 3.5
The format of the print statement is replaced in the new Python version.
Python 2:
print "Hello, World!"
Python 3:
print("Hello, World!")
I can say- Python 2 is a legacy now. Python 3 is the future.
Many companies are moving to Python 3. Some companies still using Python 2 for legacy purposes.
For example, Instagram has migrated its development from Python 2 to Python 3.
These are the properties of Python array data types like string or list.
Indexing:
Each element in the list will be having an index that describes the location of the element within the array. The index value is used to access the element at a particular location.
Indexing Example in List:
myList=["abc", "def", "ghi"] myList[0] #abc myList[1] #def myList[2] #ghi
Slicing:
This technique is used to slice the array in Python. It is required to provide the start and the end index of the string. By default, the start index will be zero and the end index will be an index of the last element in the array.
Slicing Example in String
myStr="CSEstack.org" myStr[3:8] #stack
Python has negative indexing.
The last element in the list will be having index -1, second last element will be having index -2, and so on…
This negative indexing is useful for accessing elements from the right to left.
Similar to the list, negative indexing is used to access the character in the string.
Example:
myStr="code"
print(myStr[-1])
print(myStr[-2])
print(myStr[-3])
print(myStr[-4])
Output:
e d o c
Here is a simple code you can use to reverse the string with single line of code.
myStr="csestack"
print(myStr[::-1])
Output:
kcatsesc
This is tricky questions. It was asked to me in the OVH Cloud interview.
Answer: There are four main numeric data types in Python- int, long, float and complex. There is also one more data type called boolean which is a subset of the integer data type.
List of numeric data type in Python:
An int is one of the numeric data types in Python. It is an integer value that has a precision limit of 32 bits.
You can use the sys
module to find the max and min value of the integer.
Finding the maximum value of an integer in Python:
import sys
sys.maxint
#2147483647
Finding the minimum value of an integer in Python:
import sys
-sys.maxint - 1
#-2147483648
Every object in Python falls in either mutable or non-mutable type.
Mutable object:
These are the types of object for which value can be changed after creating it.
Example:
Immutable object:
Unline mutable object, the value of the object can not be changed after creating it.
Example: There is a long list of immutable data types in Python.
The interviewer can ask you a question- “Whether specific datatype is mutable or immutable? Justify it.”
To understand it programmatically, refer mutable vs immutable objects in Python.
List Example:
myList=[2, 4, 45]
Tuple Example:
myTuple=(3, 5, 8)
There are some similarities between the list and tuple.
Reference: list vs tuple in Python
These three keyword/methods are used to remove the element from Python list. Watch this video to understand the difference between them.
Don’t forget to subscribe our YouTube channel for more Python tutorials.
This question can also be asked in different way.
“How to get the list of Built-in modules in Python?”
Run below Python command in the fresh Python installed or virtual environment.
help("modules")
It lists out all the modules that come with Python installation. You can use them by important in your Python program.
If you are applying for job-related to data analytics or web scraping, there are multiple questions you will be asked to answer.
Like…
Check web scraping interview questions to get the answers to all these questions.
The “with” statement is used while opening the file. Using the “with” statement gives us better syntax and exception handling.
Though “with” statement is optional, looking at the benefits of it, it has been standard practice using it.
You can open files with or without ‘with’ keyword. When you use ‘with’, you don’t need to close the file descriptor object manually. It will get deleted as soon as control goes out of ‘with’ block.
For a practical example, check file handling in Python.
The class defines the behavior of the instances i.e. object. Metaclass defines the behavior of another class. This is the main difference between class and metaclass.
In other words, a metaclass is a class of another class.
Not every programming language supports metaclass concepts. Python has a metaclass implementation supported.
If you are programming in Python for a while you might have come across pip. The pip is a tool for managing Python modules.
When you install any Python module using the pip tool, it downloads the that Python package to your local system and installs it.
All the Python packages are stored in its official PyPI Python packaging repository. When you mention any Python module while installing in pip tool, it looks for the Python package name in the repository. if it found, it starts installing on your local system.
To date while writing this article, there are 192,541 libraries are available on the official PyPI repository. It’s a HUGE list to explore.
Python packaging is very useful. You don’t need to write a program from scratch. You can use code which already written in Python packages. Install them and use them.
If you have written some interesting code and if you think this code is very useful for other developers around the globe, you can also propose and submit your code as a package to PyPI.
Compiled languages and interpreted languages are two different languages.
Compiled languages are the languages that are converted into machine level languages from its source code. And execute the same time. So for the programmer, it is programming languages that executed directly from the source code.
In Interpreted languages, each line of code is being translated to the machine code and executed. The complete program will not be compiled.
Distinguishing any languages between two types is based on the implementation. It is the property of the implementation, not of the Programming language.
When you run a Python program, it is executed directly from the source code. So it should be considered as interpreted languages. But there is a little twist.
How does the Python program execute?
So you can see there are multiple implementations of Python. Python programming language can fall in both the categories (compiled or interpreted) based on the implementation.
If you consider official Python programming implementation (CPython), it is not completely compiled or interpreted programming languages. But, it is byte-code interpreted programming language.
Note: If you are asked for this question in the interview, you need to explain it completely.
Range and Xrange are two functions that are generally used to create the sequence of the list.
Update: Method xrange()
is deprecated in Python 3 version so it will not be available with the latest Python version.
In Python 2, these are built-in functions.
Difference between range() and xrange().
Python uses lazy evaluation techniques.
When you use range() function, it returns an object called a generator. Instead of saving complete range values [0, 1, 23,…, 10], it saves the equation like (i=0; i<11; i+=1).
The generator computes the next value only when it is required. This technique is called as lazy evaluation.
If you have elements in a big range, the generator is useful as it saves your program memory.
Whereas, Python list stores the complete list. This one of the differences between list and generator.
Iterators and generators are the two different object types. Both these objects are used for iteration.
Unlike iterators, generators use lazy evaluation techniques (as per the explanation provided in the above question.)
Yield and generators have to relatable concepts.
To understand the above three questions practically, follow Python generators and yield tutorial.
This is one of the very common programming questions you will be asked in many of the Python technical interview rounds.
Here is a simple program.
def fibonacciGenerator():
a=0
b=1
for i in range(6):
yield b
a,b= b,a+b
obj = fibonacciGenerator()
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
Output:
1 1 2 3 5 8
There can be some variation in this program. Like writing a Python Fibonacci generator of infinite size. Be prepared for this.
In Python programming, we can copy one object to another object. There are two ways of doing that.
Deep Copy:
It copies all the content from one object to another. If you made any changes in the old object, it will not make changes in the new object.
Shallow Copy:
Instead of coping contents from one object to another, it saves the reference of an old object into the new object. When you make a change in any object (old or new), it will reflect in another object.
You can use the copy module for a deep and shallow copy.
Python example for Deep Copy and Shallow Copy:
import copy copy.copy(x) #creates shallow copy copy.deepcopy(x) #creates deep copy
Both have their pros and cons. You can use either one based on your requirements.
Here are two major differences between the two.
There are also some more differences between sorted() and sort() based on the performance and use-cases.
Also, learn the code for both sort mechanism from the Python list sorting tutorial.
In Python, lambda is a special single-line function without a function name.
Following is basic syntax and example.
obj = lambda x: x**2
print(obj(10))
Here, x is the input parameter to the lambada function which returns the square of the x (x**2).
This lambda function can be assigned to the object. The object can be used to call the lambda function.
Example:
obj = lambda x: x**2
print(obj(10))
Output:
100
Lambda function is very useful in list compression, map, reduce and filter functions.
The map is a built-in function, which takes function and list as an input and returns the new list by applying a given function on each element in the give list.
Example: Write a Python program to generate the new list where each element will be square of the element from the given list using the map function.
objFun = lambda x: x**2
li=[3, 5, 6, 7]
objMap = map(objFun, li)
print(list(objMap))
Output:
[9, 25, 36, 49]
In the above example, you are using lambda function as an input to the map function.
The filter is a built-in function in Python which is used to filter out some elements from the list.
Like map function, the filter takes two arguments- function and the list.
The function will be applied for each element in the list and returns True or False based on the condition. If the condition is False for a specific element in the list, element in the list will be eliminated.
Example: Write a Python program to finds all the odd numbers in the list using filter function?
objFun = lambda x: x%2
li=[3, 5, 6, 7, 8]
objFilter = filter(objFun, li)
print(list(objFilter))
Output:
[3, 5, 7]
Note: To use a filter, you have to pass the boolean function which returns True or False based on the condition defined in the boolean function.
The reduce function is used to reduce the elements in the list by applying a certain function.
Example: Write a program to find the sum of all the elements in the list using reduce function.
from functools import reduce
objFun = lambda x,y: x+y
li=[3, 5, 7, 9]
objReduce = reduce(objFun, li)
print(objReduce)
Output:
24
Working of reduce function:
Note: Unlike map and filter, to use reduce function you have to import it from functools
Python library which comes preinstalled with the Python.
A decorator is a special Python technique by which the behavior of the existing function can be changed without changing code inside the function.
Below is a basic example of Python decorators.
Many questions can be asked on this topic. I have already written a detail explanation about Python decorators. Go through it.
In decorators, we change the one part of the code by another programing code. This technique is also called as metaprogramming.
In programming, name mangling is used to solve the attribute name (variable or method name) issue caused by the presence of the same attribute name at different places.
This technique is also called a name decoration.
If you are working on multiple classes in your program, there can be a possibility of the overriding attribute name. The same attribute name can be present at both bases and derived class.
When you create an object of the derived class and calls the override attribute, it always calls the derived class attribute, not a base class attribute.
There is no way to distinguish override attributes in the base class and derived class.
To solve this issue and to distinguish override attributes, python uses the name mangling mechanism.
For the attribute you are overriding, add __
(double underscore) as a prefix. While execution, your attribute name will be changed as _<class_name>__<attribute>
.
By adding a class name to the attribute, you can easily distinguish base and derived class attributes.
Example:
class baseClass:
__y=20
class derivedClass(baseClass):
__y = 10
#creating object of derived class
obj=derivedClass()
print(obj._derivedClass__y)
print(obj._baseClass__y)
In the above example, we have used the name mangling for the object variable. The same name mangling technique can be applied to the class methods. For a further explanation check Python name mangling in detail.
The variable in the class is called as private when it is not accessible outside of the class. It is used only inside the class or class method.
In the case of most of the programming languages like Java, C++, you can mention private variable by specifying access modifier.
Python does not have an access modifier to define the private variable. When you add __ (double underscores) in front of any variable, it can not be accessed directly.
class myClass:
def __init__(self):
self.__y=20
obj=myClass()
print(obj.__y)
This programing will throw an error as you are trying to access the private variable (__y) outside of the class.
But this is not the complete private variable as it can be accessed outside of the class using name mangling technique. Python drops the pretense of security.
If you are using name mangling, Python encourages developers to be responsible.
A virtual environment is very useful to separate your project environment from the global Python environment on your system.
To create a virtual environment for your project, you have to install the Virtual Environment module. You can find all the Python commands for handling a virtual environment.
There can be multiple questions you will be asked in the interview like commands for creating, activating the virtual environment. So, go through the above link to learn more about the virtual environment.
Basically there are three types of methods we can define inside the class- instance method, static method and class method. All these three methods are different and we use them for a different purpose.
You can read about them in more detail at instance vs static vs class method in Python.
This is one of the questions I was asked in the NetApp interview for the MTS profile.
Python manages private heap to maintain and execute the source and byte code. It stores all the objects and data structures.
Python has a Python memory manager which is responsible for managing the memory.
We have seen earlier where I have explained- everything in Python is the object.
There are multiple entities involved while allocating memory for any object.
Here is the complete hierarchy of Python memory management depicted.
Python uses a reference count mechanism for garbage collections (deleting unwanted objects and freeing up memory).
Garbage collection is a memory management technique that is used to free up memory by deleting unwanted objects.
Python uses the reference count mechanism for garbage collection.
There are many coding questions that can be asked in the interview.
Problem statement:
The str_week_temps_f is a string with a list of Fahrenheit temperatures separated by the ‘,’ sign. Write code that uses the accumulation pattern to compute the sum and average temperature.
Example str_week_temps_f=”75.7,77.7,88.9,34.6,73.5″
Answer:
str_week_temps_f="75.7,77.7,88.9,34.6,73.5"
li_week_temps_f=str_week_temps_f.split(",")
for i in range(0,len(li_week_temps_f)):
li_week_temps_f[i]=float(li_week_temps_f[i])
sum_temp=sum(li_week_temps_f)
arv_temp=sum_temp/len(li_week_temps_f)
print(sum_temp)
print(arv_temp)
Output:
('Sum of the temperature: ', 350.40000000000003) ('Average temperature: ', 70.08000000000001)
This can be done easily with the zip built-in function.
list1=[324,45,5,34]
list2=[44,23,5,23]
print(dict(zip(list1, list2)))
Output:
{34: 23, 324: 44, 45: 23, 5: 5}
In Python 2, zip()
returns the list of tuples. In Python 3, the zip returns an iterator. You need to explicitly convert the zip()
return object into the dictionary using dict()
a built-in function.
We can use Python inbuilt function sorted().
When you pass a string to the sorted() function, it returns a list of characters in sorted order.
Then use join() string method. I will concatenate all the characters in the lost to form a single string.
Example:
strMsg="interview"
print("".join(sorted(strMsg)))
Output:
eeiinrtvw
The easiest way of doing this is, lopping over the complete list, match the desired word with each element in the list.
You can also do the same with the list comprehension technique. It is simple. One line solution.
Example:
myList=["cat", "dog", "cat", "rat"]
#find the indexes of all occuremce of "cat" in myList
indList=[ind for ind, val in enumerate(myList) if val=="cat"]
print(indList)
Output:
[0, 2]
This technique can be very useful while solving any competitive coding challenge.
This question was used in the Juniper Networks interview.
This can be easily done with the Python module named re (regular expression).
Python Program:
import re
regexIP = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''
def validateIP(strIP):
if(re.search(regexIP, strIP)):
print("Valid IP address")
else:
print("Invalid IP address")
if __name__ == '__main__' :
strIP = "122.134.3.123"
validateIP(strIP)
strIP = "44.235.34.1"
validateIP(strIP)
strIP = "277.13.23.17"
validateIP(strIP)
Output:
Valid IP address Valid IP address Invalid IP address
An empty class is nothing but the class without any variable or method inside it. It is just a place holder for class.
In Python, we can use pass
keyword to create an empty class.
#define class
class sample:
pass
#creating object of the class
obj = sample()
Especially if we are working on a new project and we are not sure about the class definition, we can create an empty class. Later, based on our requirements, we can add variables and methods in the class.
If you are new to Python programming, practice basic interview coding questions. It includes 50+ coding questions. If you practice it well, you will get a good understanding of Python.
For advanced coding practice, check out questions asked in the competitive coding challenge.
While solving these coding challenges, use different techniques like list comprehension and methods like lambda, map, filter and reduce.
The more you practice, you will feel comfortable solving coding questions whether its online test or interview round.
This question can be asked in any programming language interview. It is always good if you well understood each of these algorithms.
There are many sorting algorithms in the data structure. Like any other general-purpose programming languages, a sorting algorithm can be implemented in Python. Some of the popular sorting algorithms are
The first three sorting are simple. The last three sorting algorithms are efficient in terms of memory and time complexity.
Note:
Complexity is the evaluation technique to compare multiple algorithms based on given input values.
Time Complexity: It is justification for- How much time does a given algorithm take to execute input values of a given size?
Space Complexity: It is justification for- How much time does a given algorithm take to execute input values of a given size?
Complexity is not the property of the programming language. It is the property of the algorithm.
Every sorting algorithm has different time and memory complexity. It is just messy and not worthful to remember complexity for each and every algorithm.
Go through all the different sorting techniques mentioned above. Understand the logic behind the algorithm. Once you get the logic, it is not difficult to calculate the complexity.
MySQL is one of the very popular database management systems. Once after installing MySQL on the system, it is possible to store and retrieve data from MySQL using Python.
Install mysql-connector
Python module using the pip tool.
Import mysql.connector
to your Python program.
Here is a simple program to create a MySQL connection with Python.
import mysql.connector
myDBMS = mysql.connector.connect( host="localhost", user="your_user_name", passwd="your_password" )
After creating a connection you can try running all the basic MySQL commands to insert update and delete data entry from the database.
If you are looking for the Python developer job, many times interviewer asks you to write the Python code. They way they test your Python skill as well as your problem-solving capability.
Here are some more Python interview questions asked in different companies’ interview rounds.
These interview experiences are shared by candidates who attended the interviews.
Machine learning algorithms are implemented in these libraries which you can import in your program and use it.
There are many data science libraries available in Python. These libraries are also very useful in ML, AI, data analytics and in other domains for handling and parsing data.
Computer networking is more about network security and different communication protocols. These libraries have protocol implemented. You can use these libraries based on protocol requirements.
There are many. Listing down three here.
Django and Flask are widely used for web development. With these libraries, you can build an enterprise-level web application.
The bottle is the most lightweight framework. You can use it for any small web application.
Yes. We can build. Kivy is one of the best Python modules to use for developing a mobile application.
But, it is not recommended to use Python for mobile applications. Python lacks in speed and performance.
Whereas there are some programming languages build specifically for web development. These languages do a better job than Python.
Refer: Building an Android app using Python is Good or Bad?
This list consists covers almost all the topics from Python. If you are preparing for any specific domain like ML or AI or automation or web development, there are specific libraries in Python for each domain. Explore these Python libraries. You can expect questions on these libraries.
I will keep adding more questions and answer to this Python interview questions list. Bookmark this page so that you can refer it anytime or you can just revise it before attending any Python interview.
I spend a lot of time curating this Python questions and answering each one of them. Don’t forget to share this with your friends. I’m sure this will help many geeks if they are preparing for a job interview or if they want to enhance their Python skills.
If you have any questions specific to the Python, ask me in the comment.
All the best!
Hi All, I am a blind learner. I am also an accessibility tester. Which is the best IDE for Blind or accessible with a screen reader for Python? I am using Eclipse and VSC.