Python is a widely-used general-purpose, object-oriented, high-level programming language. The popularity of the language is due to its versatility. It is also called a scripting language used to create web applications, and develop websites and GUI applications. It helps in automation of a specific series of task that makes it more effective and adequate. In recent years, the job opportunities for Python professionals have increased, and if you are someone who is looking to start a career in profile like Python developer, data analyst with Python, full-stack developer, or backend web developer, you need to be well prepared with theoretical and technical information.
We will help you to gain expertise and crack interviews with the most frequently asked questions in Python interviews. These interview questions are the best source to advance your interview preparation. We have curated a list of some of the commonly-asked interview questions and answers to help you in your next Python interview:
Q1. What is Python?
Ans. Python is a highly readable object-oriented programming language with automatic memory management. It is the language that can be written with English keywords, while other languages use punctuations.
It is easy to learn, portable and it is open-source. It is designed to solve simple as well as complicated operations. It also supports multiple languages such as C, C++, and Java.
Q2. Explain the key features of Python?
Ans. Following are multiple features that make python different from other languages:
- Easy to learn: Python is a programmer-friendly language that it is easy to learn in just a few days. It uses fewer keywords as compared to other object-oriented languages and anyone can learn it
- Object-oriented: It is both procedure-oriented and object-oriented programming language. In procedure-oriented languages, procedures can be used again. It allows developers to use an object-oriented approach to develop applications.
- Open-source and free: It is an Open-source language that means anyone can easily access the programming and development. There is an open forum online where the number of coders contributes to improving this language.
- High-level language: It is defined as a high-level language because of this feature. You do not need to keep an eye on programming structure, memory management, and architecture of the code.
- Extendable & Scalable: It is extendable as it can be extended by using different modules to its interpreters. It helps developers to modify the program. It also provides scalability to the large codes by providing support and good structure to it.
Q3. What is PEP 8?
Ans. PEP 8 (Python Enhancement Proposal) is a Python guide used for the formatting of code. It helps to increase the readability and provide the functionality to the source code.
Q4. Why is python different from other scripting languages?
Ans. Python is different from other programming languages in many ways:
- Python is easy to read and write
- It is free. Users can easily share, copy, and edit it.
- It can be used with multiple platforms, so the programmers do not have the platform issue.
- It is an object-oriented programming language and a piece of programming code can be reusable.
Q5. Explain memory management.
Ans. In Python, memory management has different components that are allocated to do various tasks like sharing, caching, and segmentation. Python memory is managed by a private heap space. It also has a garbage collector that removes unwanted memory and free the heap space.
Q6. What is pickling and unpickling?
Ans. Pickling: It is the process in which objects are serialized and unserialized before it can be saved to the disk. It converts python objects into byte codes.
Unpickling: Unpickling is opposite to pickling as it converts byte code into python objects.
Q7. What are the modules in Python? Name some built-in modules?
Ans. Python modules are the files that contain Python statement and definitions such as –
Here, the module name is “demo.”
Python modules are used to break the large program into small segments that make the code manageable and organized.
Q8. What are the basic data types in Python?
Ans. There are five basic data types:
Q9. Mention the use of tuple?
Ans. Tuple is a data type similar to a list. It is used in programs to group the related data equivalent to the directory.
list_val = [5, 4, 3, 2]
tup_val = (5, 4, 3, 2)
[5, 4, 3, 2]
(5, 4, 3, 2)
Q10. Explain local variables and global variables.
Ans. Global variables are declared outside the function and it can be used both inside and outside the function. It has a global scope.
Local variables are those which are declared inside the function or in the local scope which cannot be used outside the function.
A combination of global and local variable declaration
def foo(x, y):
a = 62
x,y = y,x
b = 22
b = 15
c = 100
a, b, x, y = 1, 15, 2,3
print(a, b, x, y)
62 15 3 15
22 15 2 3
Q11. What is the difference between Python Arrays and Lists?
Ans. Lists and arrays both are used to store data, but the difference is that the List can any hold any data type while arrays can hold a single data type.
import array as arr
array(‘i’, [4, 3, 2, 1])
[5, ‘abc’, 1.2]
Q12. What is lambda in Python?
Ans. Lambda is a keyword used to declare any function and that function is called lambda function. It is a simple function listed as an argument.
# Python code to illustrate square of a number
# showing difference between def() and lambda().
g = lambda b: b*b
Q13. Briefly explain Functions in Python?
Ans. Functions are the small segment of code, which are reusable codes used to perform actions when it is called. “def” keyword is used to define any function in Python.
def printstar( q ):
“This prints a passed string into this function”
Q14. Is Python an Interpreted or a Compiled language?
Ans. Python is an interpreted language. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language before being executed.
Q15. Name the supported data types in Python?
Ans. There are five standard data types —
Also Read>>Top Reasons to Learn Python and Hadoop
Q16. What is a Dictionary in Python?
Ans. A Dictionary is an associative array (also known as hashes) and is like a built-in mapping.
Q17. Are arguments passed by value or reference in Python?
Ans. In Python, arguments are always passed by value.
Q18. What is Web Scraping? How do you achieve it?
Ans. Web Scraping is a way of extracting the large amounts of information available on the web sites and saving it onto the local machine or the database tables. Python has few modules for scraping the web like urllib2, scrapy, pyquery, BeautifulSoap, etc.
Q19. How do you copy an object in Python?
Ans. We can copy an object by using the functions copy.copy() and copy.deepcopy()
Q20. Name a few libraries in Python used for data analysis and scientific computations.
Ans. Some of the libraries used for data analysis and scientific computations are NumPy, SciPy, Pandas, SciKit, Matplotlib, Seaborn.
Q21. Why should one use NumPy arrays instead of nested Python lists?
Ans. NumPy’s arrays are more compact than Python lists — a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB.
Q22. What is a Python decorator?
Ans. A Python decorator is a specific change to the Python syntax that allows us to alter functions and methods more conveniently.
Q23. What is Monkey Patching? How can you do it in Python?
Ans. Monkey Patching is the process of making changes to a module or class while the program is running. A Monkey Patch is a piece of code that extends or modifies other code at runtime (typically at startup).
Q24. What is a unittest?
Ans. The unit testing framework of Python is known as unittest. It has similar features with unit testing frameworks in other languages.
Unittest supports some important concepts of object-oriented Programming:
- Test fixture
- Test case
- Test suite
- Test runner
if __name__ == “__main__”:
Q25. What is a negative index?
Ans. Python sequences can be indexed as positive and negative numbers. A negative index accesses elements from the end of the list counting backward.
Q26. What is the difference between Xrange() and range()?
Ans. Range() returns a list and Xrange() returns an Xrange object, which is kind of like an iterator and generates the numbers on demand.
Q27. Define module and package.
Ans. A module is a Python object with arbitrarily named attributes that you can bind and reference.
A Python package is simply a directory of Python module(s).
Q28. Why don’t lambda forms have statements?
Ans. It is because a lambda form is used to make a new function object and then return at runtime. Also, the syntactic framework of Python is unable to handle statements nested inside expressions.
Also Read>>The Best Way to Learn Python
Q29. What is Flask?
Ans. Flask (source code) is a Python micro web framework and it does not require particular tools or libraries.
Q30. How will you perform static analysis in a Python application or find bugs?
Ans. PyChecker can be helpful as a static analyzer to identify the bugs in the Python project. This also helps to find out the complexity related bugs. Pylint is another tool that helps check if the Python module is at par with the coding standards.
Q31.When will you use the Python Decorator?
Ans. Python Decorator is used to adjust the functions in Python syntax quickly.
Q32. Are Python strings immutable or mutable?
Ans. This is among the very commonly asked Python interview questions. Your reply should be –
Python strings are immutable. Ironically, it is not a string, but a variable with a string value.
Also Read>>5 Reasons to Learn Python!
Q33. What is a pass in Python?
Ans. Pass stands for no-operation Python statement. It means that pass is a null operation; nothing happens when it is executed.
You might come across some confusing Python interview questions, MCQ is one of them, but do not get stumped. You should be thorough with your study and be well prepared for the Python interview questions.
Q34. Now, choose the right answer –When “else” in try-except-else is executed?
- In case of any exception
- When no exception is there
- When an exception occurs in the except block
Ans. c) when no exception occurs
Q35. What is slicing?
Ans. Slicing is a computationally fast way to methodically access a range of items from sequence types like list, tuple, strings, etc.
Q36. What is the output of the following code?
list1 = [5,4,3,2,1]
list2 = list1
list2 = 0;
print “list1= : “, list1
list1= : [5,4,3,2,1]
Q37. How is the last object from a list removed?
Ans. list.pop(obj=list[-1]) − Removes and returns last object from the list.
Q38. What is docstring?
Ans. Python documentation strings (docstrings) provide an easy way to document Python functions, modules and classes.
Q39. How to delete a file?
Ans. We can delete a file in Python by using a command os.remove (filename) or os.unlink(filename).
Q40. What is the output of the following code?
x = True
y = False
z = False
if x or y and z:
Reason: Here, in Python AND operator has a higher preference than OR operator. So, (y and z) are evaluated first.
Q41. How many kinds of sequences does Python support? Name them.
Ans. Python supports seven sequence types –
- byte array
Q42. How will you reload a Python module?
Ans. reload() is used to reload a previously imported module.
Q43. What is a set?
Ans. A set is an unordered collection of iterable and mutable data, and it has no duplicate elements.
Q44. Name some standard Python errors.
Ans. Some standard errors are –
We can use dir(__builtin__) to list all the errors.
Q45. What is Tkinter?
Ans. Tkinter is the de-facto standard GUI (Graphical User Interface) package of Python.
Q46. What is multithreading?
Ans. Multithreading stands for running a number of programs simultaneously by invoking multiple threads.
Q47. How is a list reversed?
Ans. To reverse lists, one can use list.reverse()
Q48. How to capitalize the first letter of string?
Ans. To capitalize the first letter of the string, capitalize() method is used. If the string is already capitalized then it will return the original value.
Q49. Which python library is used for Machine learning?
Ans. Scikit-learn python Library is used for Machine learning.
Q50. What is the role of len() in python?
Ans. len() is used to determine the length of an array, list and string in the program.
Q51. What is the output of the following code?
def __initl__(self, id):
self.id = id
id = 777
acc = Acc(222)
Ans. Output: 222
Reason: “Demo” class automatically calls the method ”initl” and passes the object and “222” is assigned to the object called id. So, the value “777” cannot be called and the output will be “222”.
Q52. How to delete a file in Python?
Ans. OS Module needs to be installed to delete any file. After installing the module, os.remove() function is used to delete a file.
Q53. Write a code to test whether the number is in the defined range or not?
if n1 in range(0, 555):
print(”%s is in range”%str(n1))
print(”%s is not in range”%str(n1))
555 is not in the range
Q54. Write a code to convert a string into lowercase?
Ans. lower() is used to convert the string into lower case
Q55. What is the output of the following code?
nameList = [‘Joe’, ‘Nick’, ‘Bob’, ‘Harry’]
Reason: [-1] shows the last element or character of the string. In the above code, ]1] represents the second string and [-1] represents the last character of the second string, i.e., “k.”
Q56. Which databases are supported by Python?
Ans. MySQL (Structured) and MongoDB (Unstructured) are supported by Python. First, the modules should be imported to the library to interact with the database.
Q57. What is the output of the following code?
demoCodes = [1, 2, 3, 4]
Ans. Output: 5
Reason: ‘append’ method is used in the code, which has to append the existing object into the list. But the append method does not merge the list, which is added as an element. So, the output will be’5’.
Q58. What is the use of the ‘#’ symbol in Python?
Ans. ‘#’ symbol is used to symbolize the comments
print (“I am a quick learner”)
#print (“I am a quick learner”)
Q59. Suppose a list1 is [2, 44, 191, 86], what would be the output for list1[-1]
Ans. Output: 86
List1[-1] shows the last integer of the list
Q60. What is the maximum length of an identifier?
Ans. The maximum possible length of an identifier in python is 79 characters
Q61. Can you tell me the generator functions in Python?
Ans. Generator functions help to declare a function that behaves like an iterator in a fast, easy, and neat way.
Q62. Write a code to display the current time.
Ans. Here is the code to represent the current time:
now = datetime.datetime.now()
print (“Current date and time : “)
print (now.stgftime(“%Y-%m-%d %H:%M:%S”))
Q63. Is Python a case-sensitive programming language?
Ans. Yes, it is a case-sensitive language like other languages such as Java, C, and C++.
Q64. Write a code to sort a numerical list in Python.
Ans. To sort a numerical list, use the following code:
list = [“2”, “7”, “3”, “5”, “1”]
list = [int(i) for i in list]
Q65. Write a code to display the contents of a file in reverse.
Ans. To reverse the content, use the following code:
for line in reversed(list(open(filename.txt))):
Q66.How to add array elements in programming?
Ans. We can add elements to an array with the help of append(), insert (i,y) and extend() functions.
x=arr.array(‘d’, [1.2 , 2.2 ,3.2] )
array(‘d’, [1.2, 2.2, 3.2, 3.3])
array(‘d’, [1.2, 2.2, 3.2, 3.3, 4.5, 6.2, 6.3])
array(‘d’, [1.2, 2.2, 3.8, 3.2, 3.3, 4.5, 6.2, 6.3])
Q67. Why is the split used in Python?
Ans. The split() method is used to separate two strings.
Output: [‘Naukri’, ‘learning’]
Q68. How to create classes in Python?
Ans. Classes are user-defined which is defined with a class keyword
def_init_(self, name) :
self.name = name
S1 = Student (“xyz”)
Q69. How do we create an empty class?
Ans. An empty class is a blank class that does not have any code defined within its block. We can create an empty class using the pass keyword.
print (“Name = “,obj.name)
Name = xyz
Q70. Write a program to check if a sequence is a Palindrome.
Ans. To check a sequence whether it is palindrome or not:
x=input (“enter sequence”)
print (“Not a Palindrome”)
enter sequence 323 Palindrome
Q71. Mention the differences between Django, Pyramid, and Flask?
Ans. Following are the difference between Django, Pyramid, and Flask:
- Flask is used to create small applications with simpler necessities. It requires external libraries to built applications, and you are ready to use it.
- The Pyramid is used to create large applications. It is heavy configurable and requires a database, templating style, URL structure, and other elements to build an application. It also provides flexibility to choose the right tools for development.
- Django is also used for large applications that is similar to the Pyramid. It consists of an ORM.
Q72. Explain the difference between a shallow copy and a deep copy?
Ans. Shallow copy is used at the time of new instance creation, and it stores the copied values whereas in deep copy, the copying process executes in looping, and copy of an object is copied in other objects. A shallow copy has faster program execution than a deep copy.
Q73. Which statement can we use if the statement is required syntactically, but no action is needed for the program?
Ans. Pass statement is used if the statement is required syntactically, but no action is required for the program
Q74. What are the tools required to unit test your code?
Ans. To test units or classes, we can use the “unittest” python standard library. It is the easiest way to test code, and features required are similar to the other unit testing tools like TestNG, JUnit.
Q75. How to get indices of N maximum values in a NumPy array?
Ans. With the help of below code, we can get the N maximum values in a NumPy array :
Import numpy as nm
arr=nm.array([1, 6, 2, 4, 7])
print (arr.argsort() [-3:] [::-1])
[ 4 6 1 ]
Q76. How can you use ternary operators (Ternary) in Python?
Ans. Ternary operators are used to display conditional statements. This consists of the true or false values. Syntax :
The ternary operator is indicated as:
[on_true] if [expression] else [on_false] x, y = 25, 50big = x if x <y else y
Example: The expression is evaluated as if x <and else and, in this case, if x <y is true, then the value is returned as big = x and if it is incorrect then big = y will be returned as a result.
Q77. What does this mean? * args, ** kwargs? Why would we use it?
Ans. * Args is used when you are not sure how many arguments to pass to a function, or if you want to pass a list or tuple of stored arguments to a function.
** kwargs is used when we don’t know how many keyword arguments to pass to a function, or it is used to pass the values from a dictionary as the keyword argument.
The args and kwargs identifiers are a convention, you can also use * bob and ** billy but that would not be wise
Q78. Does Python have OOps concepts?
Ans. Python is an object-oriented programming language. This means that any program can be solved in Python, creating an object model. However, Python can also be treated as a procedural and structural language.
Q79. What is the compilation and linking process in Python?
Ans. Compilation and binding in Python allow new extensions to compile without any errors and binding can only be done when the build procedure passes. If dynamic loading is used, then it depends on the style supplied with the system. The Python interpreter can be used to provide dynamic loading of configuration files and rebuild the interpreter.
For this, the steps required in the process are:
Create a file with a name and in any language, which is compatible with your system compiler, example, file.co file.cpp
Locate the file in the Modules / directory of the distribution you are using.
Add a line in the Setup.local file that is present in the Modules / directory.
Run the file using spam file.o
After successful execution of this rebuild, the interpreter uses the make command in the top-level directory.
If the file is changed, then run rebuildMakefile using command like ‘make Makefile’.
Q80. Is Django better than Flask?
Ans. Django and Flask map URLs or addresses typed in web browsers to Python functions.
On a technical level, both are good and have their own advantages and disadvantages but Flask is simpler compared to Django but, Flask does not do much for you. This means that you have to specify the details, while Django does much more, for which the user would not have to write excess code.
This is because Django consists of pre-written code that the user will need to parse while Flask gives users the ability to create their own code. Therefore, it is easier to understand the code.
Q81. How do I save an image locally using Python whose URL I already know?
Ans. We will use the following code to store an image locally from a URL
urllib.request.urlretrieve (“URL”, “file-name.jpg”)
Q82. How can you get the time (age) of the Google cache of any URL or web page?
Ans. Using the following URL format:
You should make sure to replace “EL-URL-GO-HERE” with the correct web address of the page or site to get the age of the Google cache.
Example – To check the age of Unipython’s Google web cache, you would use the following URL:
Q83. What is the map function in Python?
Ans. The map function takes two arguments, one is iterable and another is a function, and applies the function to each element of the iterable. If the given function accepts more than 1 argument then many iterables are given.
Q84. How are percentages calculated with Python / NumPy?
Ans. Percentages can be calculated using the following code:
import numpy as np
a = np.array ([1,2,3,4,5])
p = np.percentile (a, 50) #Returns 50%.
Q85. What is the difference between NumPy and SciPy?
Ans. Both NumPy and SciPy are modules of Python, and they are used for various operations of the data. NumPy stands for Numerical Python while SciPy stands for Scientific Python. The main differences are –
|Makes Python an alternative to MatLab, IDL, and Yorick||A collection of tools for Python, used for general numerical computing in Python|
|Used for efficient operation on homogeneous data that are stored in arrays||Support operations like integration, differentiation, gradient optimization, etc.|
|Multi-dimensional array of objects, used for basic operations such as sorting, indexing, and elementary functioning on the array data type||No related array or list concepts as it is more functional|
|Suitable for computation of data and statistics, and basic mathematical calculation||Suitable for complex computing of numerical data|
Q86. How 3D graphics/visualizations are made using NumPy / SciPy?
Ans. Like 2D plotting, 3D graphics are beyond the scope of NumPy and SciPy, but there are packages that can be integrated with NumPy. However, Matplotlib supplies basic 3D plotting in the mplot3d sub-package, while Mayavi offers a host of high-quality 3D viewing features, using the powerful VTK engine.
Q87. What is PYTHONPATH?
Ans. It is an environment variable and is used when importing a module. In addition, PYTHONPATH is used to check the presence of imported modules in some directories. The interpreter uses it to determine which module to load.
Q88. How to install Python on Windows and set a path variable?
Ans. – Install Python from this link: https://www.python.org/downloads/
– After that, install it on your PC. Find the location where Python has been installed on your PC using the following command on the command line: cmd python
– Go to advanced system settings and add a new variable and name it PYTHON_NAME, and paste the copied path
– Find the path variable, select its value and select ‘edit’
– Add a semicolon after the value if it is not present and then write% PYTHON_HOME%
Q89. Is indentation required in Python?
Ans. Indentation is very necessary in Python. It specifies a block of code. All the code within classes, functions, loops, etc., is specified within an indented block. Generally, this is done using four space characters. If your code is not indented, it will not execute accurately and will throw errors.
Q90. What is the Self in Python?
Ans. The Self in Python is an instance or object of a class. It is explicitly included as the first parameter. This helps distinguish between methods and attributes of a class with local variables.
The variable self in the init method refers to the newly created object while in other methods; it refers to the object whose method was called.
Q91. How does break, continue and pass work?
Ans. Break – It allows the termination of the loop when some condition is met and control is transferred to the next instruction.
Continue – Lets you skip some part of a loop when a specific condition is met and control is transferred to the beginning of the loop.
Pass – It is used when a block of code is needed syntactically, however, its execution needs to be skipped. This is a null operation. Nothing happens when this runs.
Q92. What are the iterators in Python?
Ans. Iterators in Python are objects used to iterate all the elements of a collection.
Q93. How can you generate random numbers in Python?
Ans. The random module is the standard module for generating a random number. The method is defined as:
The random.random () declaration returns the floating point number that is in the range of [0, 1]. The function generates random floating numbers. The methods used with the random class are the bound methods of the hidden instances.
Random instances can be made to display multithreading programs that create a distinct instance of individual threads. The other random generators used are:
randrange (a, b): choose an integer and define the range between [a, b). Returns elements by randomly picking them from the specified range. It does not construct a range object.
Uniform (a, b): select a floating point number that is defined in the range of [a, b). It returns the floating-point number.
normalvariate (mean, sdev): used for normal distribution where mu is mean and sdev is sigma used for standard deviation.
Q94. What is the Dogpile effect?
Ans. This is one of those difficult Python interview questions to memorize at first, so give it a few tries.
The Dogpile effect occurs when a website’s cache has expired and it is hit by numerous requests the same time. This causes a variety of problems, from increased large lag to massive errors.
A system called traffic light blocking is used to prevent the effect of Dogpiles.
Q95. Explain what is encapsulation?
Ans. Encapsulation is one of the characteristics of the Python language because it is an object-oriented programming language.
Encapsulation is the process of grouping data sets in one and only place. Along with members, encapsulation also returns functions.
Q96. When does Abnormal Termination occur?
Ans. First of all, I should mention that abend or abnormal termination is bad. You don’t want it to happen during your programming experience. However, it is practically unavoidable, in one way or another especially when you are a beginner.
Abend is an error in your program during its execution, while the main tasks continue to perform processes. This is caused by a code error or some software problem.
Q97. Does the Python language have a compiler?
Ans. This is one of the most difficult Python interview questions, especially since so many people don’t pay attention to it.
Python clearly has a compiler, but it is very easy to miss. This is because it works automatically, you won’t even notice.
Q98. What is polymorphism in Python?
Ans. Polymorphism is the ability to take many forms, for example, if the parent class has a method called ABC, it means that the child class can have a method with the same name ABC. This contains its own parameters and variables. Polymorphism is allowed in Python.
Q99. How is data abstraction done in Python?
Ans. It can be achieved in Python using abstract classes and interfaces. Data abstraction only supplies necessary details and hides the implementation.
Abstraction is selecting data from a larger pool to show only the relevant details to the object.
Q100. Does Python use access specifiers?
Ans. Python does not have access modifiers. Rather it establishes the concept of prefixing the variable, method, or function name with a single or double underscore to mimic the behavior of the private and protected access specifiers.
We have created a collection of best python interview questions to help you prepare for your upcoming interview questions. It includes theoretical information, technical skills, interpersonal, algorithms, and coding questions which are frequently asked in the interview sessions.
In case you have recently completed a professional course/certification,