Python Interview Questions From Shiksha
Python Interview Questions From Shiksha
Atul Harsha
Senio r Manager Co ntent
If you are someone who is looking to start a career as a Python developer, data analyst with
Python, f ull-stack developer, or backend web developer, then this Python interview
questions guide will help you to gain expertise by providing the most f requently asked
questions in Python interviews.
This is how a general Python interview round in a product based company like
Google, Microsoft, Facebook, Adobe look like:
Interviewer will introduce himself and explain his role (in this case, a SD3).
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
T he candidate will be asked to brief ly introduce themselves and describe their experience
with Python.
What are the key dif f erences between Python 2 and Python 3?
How does Python’s asyncio work? Provide an example where it might be usef ul.
Explain the dif f erence between new and init in Python’s class construction.
Provide a real-world problem for the candidate to solve. This will test their problem-
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
solving skills and their ability to write clean, efficient Python code. For example:
Problem Statement: Given a large log f ile with timestamps, IP addresses, and error
messages, write a Python script to identif y the IP addresses that have the highest
occurrence of a specif ic error message.
Discuss a system design problem that requires integrating Python. For instance:
Design a recommendation system f or a streaming service. How would you use Python to
process and analyze the data?
What attracts you to Microsof t and how do you see yourself contributing here?
Remember, the goal of the interview is not just to assess the candidate’s technical
skills, but also their problem-solving abilities, cultural fit, and communication skills.
Table of Content
Python Interview Questions asked in T op Companies
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Practical Coding Question
SD1 Level Question
Company
Interview Question
Name
2. Describe the dif f erences between Python 2 and Python 3. How would you
Facebook
handle a migration f rom Python 2 to Python 3 in a large codebase?
4. Explain the GIL (Global Interpreter Lock) in Python. How does it af f ect
Netflix
multi-threaded applications?
5. Describe how Python’s garbage collection works. How can you manually
Microsoft
trigger garbage collection?
6. How would you optimize a Python application that reads and processes
Apple
large f iles?
7. Explain the dif f erences between “deep copy” and “shallow copy” in
LinkedIn
Python. When would you use each?
Oracle 9. Describe the dif f erences between a list, tuple, and set in Python.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
12. Describe how you would implement authentication and authorization in a
Uber
Python web application.
Salesforce 13. How would you handle logging in a distributed Python application?
15. How would you handle database migrations in a Python web application
Airbnb
using an ORM?
Z oom 16. Describe the use of Python’s “with” statement and its benef its.
Nvidia 17. How would you optimize a Python application f or GPU processing?
Atlassian 18. Describe how you would implement a REST f ul API in Python.
20. Explain how Python’s “asyncio” works and how it can be used f or
T esla
asynchronous programming.
Here are the top commonly asked Python interview questions that will help you advance
your interview preparation.
Q1. What is t he dif f erence bet ween Pyt hon 2 and Pyt hon 3?
Unicode Strings Implicitly treats as ASCII Strings are Unicode by def ault
except Exception, e:
Exceptions except Exception as e: syntax
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Exceptions except Exception as e: syntax
syntax
Iterators and
itertools.izip() f or zipping zip() behaves like itertools.izip()
Iteration
Standard Library
Library names may dif f er Some library reorganizations
Changes
Ans. Following are multiple f eatures that make python dif f erent f rom other languages:
Easy to learn: Python is a programmer-f riendly language that it is easy to learn in just a
f ew days. It uses f ewer keywords as compared to other object-oriented languages and
anyone can learn it
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
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. T here is an open f orum online where the
number of coders contributes to improving this language.
High-level language: It is def ined as a high-level language because of this f eature. You
do not need to keep an eye on the programming structure, memory management, and
architecture of the code.
Extendable & Scalable: It is extendable as it can be extended by using dif f erent modules
to its interpreters. It helps developers to modif y the program. It also provides scalability to
the large codes by providing support and good structure to it.
Must Read: Introduction to Python – Features, Use Cases, Resources, and Applications
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Aspect Lists T uples
For collections of items that may For collections that should not
Use Case
change change
Immutability Used when data should be changed Used when data should remain
Use or updated constant
Remember that while the table provides a quick overview of the differences, the
choice between using a list or a tuple in Python depends on the specific
requirements of your code.
Ans. PEP 8, also known as Python Enhancement Proposal 8, is the official style
guide for writing Python code. It outlines a set of conventions and
recommendations for formatting code to ensure consistency and readability, making
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
it easier for developers to collaborate on projects.
Copy code
class Person:
def __init __(self , name, age):
self .name = name
self .age = age
alice.greet ()
bob.greet ()
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
In this example, the code adheres to several PEP 8 principles:
Indentation: Code is indented using f our spaces.
Naming Conventions: Function and variable names are in lowercase with words
separated by underscores (calculate_square, alice, bob).
Comments: Comments are used to explain the purpose of f unctions and classes.
By following PEP 8, your code becomes more consistent and easier to read, which is
especially helpful when working on collaborative projects or maintaining code over
time.
Q5. How is Pyt hon dif f erent f rom ot her script ing languages?
Ans. Python as a scripting language is dif f erent f rom other programming languages in
dif f erent ways . Let’s compare some of the popular scripting language like Perl, Ruby,
and Bash with Python.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Feature/Aspect Python Perl Ruby Bash
“Z en of Inf luenced by
“T here’s more Command
Development Python”, Perl & Smalltalk,
than one way to execution, Unix
Philosophy simplicity, natural
do it”, f lexibility scripting
readability readability
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
you’re essentially asking Python, “Hey, can I have a small space in this room to store
my stuff?” Python then takes care of finding the right spot for you.
Private Heap Space:
T hink of this as a special section of the storage room where Python keeps all the
things (objects, data) you create.
Python maintains an internal private heap, where all objects and data structures are
stored and managed by the Python memory manager.
Reference Counting:
Imagine you have a toy (an object) in the storage room. Every time you play with it
(use the object), you add a sticker to it. When you’re done playing (stop using the
object), you remove a sticker. If the toy has no stickers lef t, Python knows no one is
playing with it, so it can be thrown away to f ree up space. T his is what ref erence
counting is.
Python uses ref erence counting as a primary memory management technique. Every
object has a count of the number of ref erences pointing to it. When this count drops
to zero, the memory occupied by the object can be reclaimed.
Garbage Collection:
Over time, some toys might get f orgotten in the corner, even if they have no stickers.
Every once in a while, Python sends a cleaner (garbage collector) to f ind and remove
these f orgotten toys, ensuring the room doesn’t get too cluttered.
Q7. What are t he modules in Pyt hon? Name some built -in modules.
Ans. In Python, a module is a file containing Python definitions and statements. The
file name is the module name with the suffix .py is added. Modules are a way to
organize related code into a single file, making the code easier to understand and
use. They can define functions, classes, and variables, and can also include runnable
code.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
In other words, a module is like a file that holds related pieces of code. This file ends
with “.py“. Think of it as a folder on your computer where you store similar photos or
documents. Just as you might have a folder for vacation photos, a module groups
related functions, classes, and other code. This makes it easier to find, use, and
understand that code.
Python modules are the f iles that contain Python statement and def initions such as –
E.g., arithmetic.py
Copy code
In the above module (arithmetic.py), we have defined four functions: add, subtract,
multiply, and divide.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Now, if you want to use these functions in another Python script, you can simply
import the arithmetic module and access its functions.
Copy code
Python modules are used to break the large program into small segments that make the
code manageable and organized.
Code Reusability: Once you’ve written a module, you can reuse it across multiple
programs.
Namespace Partitioning: Modules help avoid naming conf licts by creating a separate
namespace f or identif iers.
Organizing Large Projects: For bigger projects, organizing code into dif f erent
modules and packages is essential f or maintainability.
math: Provides mathematical f unctions. For example, math.sqrt() computes the square
root.
sys: Provides access to Python interpreter variables. For instance, sys.argv gives
command-line arguments.
os: Of f ers a way to use operating system-dependent f unctionality like reading or writing
to the f ile system.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
collections: Implements several specialized container datatypes like named tuples,
deques, and Counters.
gc: Provides an interf ace to the garbage collection f acility of the Python interpreter.
These are just a few of the many built-in modules in Python. You can use the
help(‘modules’)command in the Python interpreter to see a complete list of available
modules.
Q8. How do you convert a st ring t o an int eger and vice versa in Pyt hon?
Copy code
st ring_num = "123"
int _num = int (st ring_num)
print (int _num) # Outputs: 123
print (t ype(int _num)) # Outputs: <class 'int'>
Note: The string should represent a valid integer. If you try to convert a string that
doesn’t represent an integer (e.g., “123.45” or “abc”), you’ll get a ValueError.
Converting an Integer to a String:
T o convert an integer to a string, you can use the str() f unction.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
These conversions are commonly used in various scenarios, such as reading input
from users, processing data from files, or formatting output.
In Python, you can merge two dictionaries in several ways. Here are some of the
most common methods:
Using the update() method:
T his method modif ies the f irst dictionary in place by adding keys and values f rom the
second dictionary.
Copy code
Note: If the second dictionary has keys that are already present in the first
dictionary, their values will be updated in the first dictionary.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Read More: Dictionary in Python
Copy code
Copy code
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
All of these methods will effectively merge two dictionaries. The choice of method
often depends on the specific requirements and the Python version being used.
Q10. What ’s t he dif f erence bet ween append() and ext end() met hods of a list ?
Both append() and extend() are methods of a list in Python, but they serve different
purposes:
append() adds its entire argument as a single element to the end of the list.
extend() adds each element of its argument to the list. T he argument should be an
iterable.
append() method:
T he append() method adds its entire argument as a single element to the end of the list.
T he new length of the array will be len(list) + 1.
Example:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
list 1 = [1, 2, 3]
list 1.append(4)
print (list 1) # Outputs: [1, 2, 3, 4]
In the second example, you can see that the entire list [5, 6] is added as a single
element to list1.
extend() method:
T he extend() method takes an iterable (like a list, tuple, string, etc.) and adds each of its
elements to the list.
T he new length of the array will be len(list) + len(iterable).
Example:
Copy code
list 1 = [1, 2, 3]
list 1.ext end([4, 5])
print (list 1) # Outputs: [1, 2, 3, 4, 5]
In the examples above, each element of the iterable passed to extend() is added
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
In the examples above, each element of the iterable passed to extend() is added
individually to list1.
Example:
Copy code
st ring = "Hello"
reversed_st ring = st ring[::-1]
print (reversed_st ring) # Outputs: "olleH"
String slicing is a technique in Python to extract a portion (or slice) of a string. It uses
the format:
Copy code
start: T he beginning index of the slice. It’s inclusive, which means the slice starts at this
index. If omitted, it def aults to 0 f or positive step values and -1 f or negative step values.
stop: T he ending index of the slice. It’s exclusive, which means the slice goes up to, but
does not include, this index. If omitted, it def aults to the end of the string.
Example:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
Q13. How would you check if a subst ring exist s wit hin a st ring?
You can use the in keyword to check if a substring exists within a string.
Example:
Copy code
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Example:
Copy code
Syntax: Lists are def ined using square brackets [] , whereas tuples are def ined using
parentheses ().
Q15. Can you modif y an element inside a t uple? Why or why not ?
No, you cannot modify an element inside a tuple. This is because tuples are
immutable. Once a tuple is created, you cannot change, add, or remove elements
from it. This immutability provides certain advantages in terms of data safety and
can also lead to performance improvements in some scenarios.
Using a tuple over a list is often a matter of context and the specific requirements of
a problem. Here are some scenarios where a tuple might be preferred over a list,
along with examples:
1. Data Integrity:
When you want to ensure that the data remains constant and doesn’t get modified
accidentally, tuples are a safer choice because they are immutable.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Example : Representing the coordinates of a point in a 3D space.
Copy code
Reason : Coordinates of a point are fixed values and should not change once
defined. Using a tuple ensures that these values remain constant and cannot be
accidentally modified, preserving data integrity.
Tuples can be used as keys in dictionaries because they are hashable, whereas lists
are not.
Example : Imagine you want to store distances between cities. The pair of cities can
be a tuple which acts as a key in a dictionary.
Copy code
dist ances = {
('New York', 'Los Angeles'): 2451,
('Houst on', 'Chicago'): 1089
}
Reason : Dictionary keys need to be hashable and immutable. Lists are mutable and
therefore cannot be used as dictionary keys. Tuples, being immutable, can serve as
dictionary keys, allowing us to represent a pair of cities as a single key.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
When functions return multiple values, they are packed into tuples.
Example : A function that returns both the quotient and remainder of a division
operation.
Copy code
result = divide(10, 3)
print (result ) # Outputs: (3, 1)
Reason : When a function returns multiple values, they are packed into a tuple by
default. This allows for a clean and efficient way to return multiple pieces of data
from a function without needing to create a specific data structure.
Tuples are often used for packing multiple values together and then unpacking them
elsewhere in the code.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
a=5
b = 10
a, b = b, a
print (a, b) # Outputs: 10 5
Reason: Tuples allow for a concise way to pack and unpack values. In the swapping
example, the values of a and b are packed into a tuple and then immediately
unpacked in a swapped order. This makes the code more readable and eliminates
the need for a temporary variable.
5. Performance :
For read-heavy operations where the data doesn’t change, tuples can be slightly
faster than lists because of their static nature.
Example : If you have a static set of values that you’re iterating over frequently, a
tuple might offer better performance.
Copy code
Reason: Tuples can be slightly faster than lists for read-heavy operations due to
their static nature. If the data set is not going to change and is frequently accessed,
using a tuple can offer a minor performance advantage.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
There are several ways to remove duplicates from a list in Python. Here are some of
the most common methods:
1. Using a Set:
Converting a list to a set will automatically remove duplicates because sets cannot
have duplicate values. However, this method does not preserve the original order of
the list.
Copy code
my_list = [1, 2, 2, 3, 4, 4, 5]
no_duplicat es = list (set (my_list ))
print (no_duplicat es) # The order might change, e.g., [1, 2, 3, 4, 5]
Copy code
my_list = [1, 2, 2, 3, 4, 4, 5]
no_duplicat es = []
[no_duplicat es.append(x) f or x in my_list if x not in no_duplicat es]
print (no_duplicat es) # Outputs: [1, 2, 3, 4, 5]
3. Using dict.fromkeys():
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
my_list = [1, 2, 2, 3, 4, 4, 5]
no_duplicat es = list (dict .f romkeys(my_list ))
print (no_duplicat es) # Outputs: [1, 2, 3, 4, 5]
4. Using a Loop:
Copy code
my_list = [1, 2, 2, 3, 4, 4, 5]
no_duplicat es = []
f or it em in my_list :
if it em not in no_duplicat es:
no_duplicat es.append(it em)
print (no_duplicat es) # Outputs: [1, 2, 3, 4, 5]
Each of these methods has its own advantages. The choice of method often
depends on the specific requirements of the problem, such as whether the original
order of the list needs to be preserved.
In Python, the scope of a variable refers to the region of the code where a variable
can be accessed or modified. The scope determines the visibility of a variable in
different parts of the code. There are four primary types of variable scopes in
Python:
Local Scope:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
A variable declared inside a f unction or method has a local scope.
It is only accessible within that f unction or method and not outside of it.
T he variable is created when the f unction is called and destroyed once the f unction
exits.
Example :
Copy code
Example :
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
3. Global Scope :
A variable declared outside of all f unctions, methods, or classes has a global scope.
If you need to modif y a global variable f rom within a f unction, you must declare it using
the global keyword inside that f unction.
Example :
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
4. Built-in Scope :
T his scope encompasses all the built-in names in Python, such as f unctions (print, len,
etc.) and exceptions (ValueError, T ypeError, etc.).
Example :
Copy code
Q19. Explain t he dif f erence bet ween local variables and global variables.
Ans. Global variables are declared outside the f unction and it can be used both inside and
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
outside the f unction. It has a global scope.
Local variables are those which are declared inside the f unction or in the local scope which
cannot be used outside the f unction.
Variables def ined inside a f unction or Variables def ined outside of all
Definition
method. f unctions and methods.
Accessible only within the f unction they Accessible throughout the entire
Scope
are def ined. module or f ile.
Let’s understand this with the help of an analogy. Imagine a house where each room
represents a function in Python. The items inside each room are like local variables,
and the items outside in the garden or on the porch are like global variables.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Local Variables (Items inside a Global Variables (Items in the
Aspect
room) garden/porch)
NOT E:
Just like you can’t use a toy f rom the bedroom while you’re in the kitchen (unless you
bring it with you), you can’t access a local variable outside its f unction.
T he garden gnome, visible f rom multiple rooms, is like a global variable. Everyone knows
it’s there, and with the right declaration, anyone can change its color. But if everyone
starts painting the gnome without caution, it can lead to conf usion about its current color,
just as overusing global variables can lead to unpredictable code behavior.
Example:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
def bedroom():
# Local Variable (Toy inside the bedroom)
t oy_color = "red"
print (f "In t he bedroom, my t oy is {t oy_color}.")
print (f "From t he bedroom, I see a {garden_gnome_color} garden gnome.")
In this example:
T he garden_gnome_color is a global variable, representing the garden gnome that can
be seen f rom multiple rooms.T he toy_color in the bedroom f unction and the mug_color in
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
the kitchen f unction are local variables, representing items specif ic to those rooms.
T he paint_gnome f unction allows us to change the color of the garden gnome, and we
declare that we’re modif ying the global variable using the global keyword.
Q20. What is t he dif f erence bet ween Pyt hon Arrays and List s?
Import
No, it’s a built-in data type. Yes, you need to import array.
Required
Data T ype Lists can store elements of Arrays store elements of the same data
Homogeneity mixed data types. type.
It’s important to note that while Python’s list is more commonly used due to its
flexibility, the array module provides a more space-efficient way to store data of a
single type, especially useful in scenarios where performance and memory usage are
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
crucial.
Q21. What ’s t he dif f erence bet ween argument s and paramet ers?
Parameters are the names listed in the f unction def inition. T hey act as placeholders f or
the values you’ll pass into the f unction when you call it.
Arguments are the actual values that you pass into a f unction when you call it. T hese
values get assigned to the parameters and are used within the f unction.
Example:
Copy code
Q22. How can you def ine a f unct ion wit h def ault argument values?
You can provide default values to parameters by using the assignment operator (=)
in the function definition. If an argument for that parameter is not provided when
calling the function, the default value will be used.
Example:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
Q23. What are posit ional argument s and keyword argument s? Provide
examples.
Positional Arguments: T hese are arguments that are passed in order and are assigned
to parameters based on their position.
Keyword Arguments: T hese are arguments passed by explicitly naming the parameter
along with its value. T hey can be provided in any order.
Example:
Copy code
Q24. How can you pass a variable number of argument s t o a f unct ion?
You can use *args to pass a variable number of positional arguments. Inside the f unction,
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
args will be a tuple containing all the passed positional arguments.
For a variable number of keyword arguments, you can use **kwargs. Inside the f unction,
kwargs will be a dictionary containing all the passed keyword arguments.
Example:
Copy code
def display_names(*names):
f or name in names:
print (name)
Q25. Explain t he use and purpose of *args and **kwargs. How do t hey dif f er?
Ans:
*args:
Analogy: T hink of *args as the “scoop” option. You tell the server you want ice cream and
just start counting the number of scoops: “1 scoop, 2 scoops, 3 scoops…”. You don’t
specif y anything else, just the number of scoops.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Simple Explanation: *args lets you send any number of single items (like scoops of ice
cream) to a f unction.
Example:
Copy code
def order_scoops(*scoops):
print (f "Ordering {len(scoops)} scoops of ice cream!")
f or scoop in scoops:
print (f "One scoop of {scoop} f lavor.")
**kwargs:
Analogy: Now, think of **kwargs as the “sundae” option. For a sundae, you don’t just
count scoops. You specif y: “1 scoop vanilla, 1 scoop chocolate, with nuts, no cherry on
top”. Each part of your order has a name (like “vanilla” or “chocolate”) and a
corresponding value (like “1 scoop” or “with nuts”).
Simple Explanation: **kwargs lets you send items with specif ic names and values (like
ingredients in a sundae) to a f unction.
Example:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
NOT E:
*args allows you to pass any number of positional arguments, which are then accessed
as a tuple.
**kwargs allows you to pass any number of keyword arguments, which are then accessed
as a dictionary.
Ans: A lambda function in Python is a small, anonymous function that can have any
number of arguments but can only have one expression. The expression is
evaluated and returned when the lambda function is called. Lambda functions are
used for creating quick functions without the need to formally define a function
using the def keyword.
Analogy: Imagine you’re at a café, and instead of ordering a regular menu item (like a
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
sandwich or a salad), you just want a quick snack. Instead of going through the
whole process of looking at the menu, deciding on an item, and placing an order,
you simply ask for a piece of fruit from the counter. It’s quick, it’s simple, and it
doesn’t need a lot of preparation or presentation.
In this analogy:
T he regular menu items (sandwich, salad) are like standard f unctions def ined using the
def keyword. T hey have a name, they can be complex, and they can perf orm multiple
tasks.
T he piece of f ruit f rom the counter is like a lambda f unction. It’s quick, nameless, serves a
single purpose, and doesn’t require a lot of f ormalities.
Copy code
Copy code
add = lambda x, y: x + y
Q27. How would you writ e a lambda f unct ion t o square a number?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
Copy code
Q28. Can lambda f unct ions have mult iple input s? If so, provide an example.
Copy code
add = lambda x, y: x + y
print (add(3, 4)) # Outputs: 7
Similarly, you can have more than two inputs if needed. For instance, to find the
product of three numbers:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
product = lambda x, y, z: x * y * z
print (product (2, 3, 4)) # Outputs: 24
Q29. How does t he ret urn st at ement work in Pyt hon f unct ions?
The return statement in Python is used to send a value back from a function to the
place where the function was called. When a function encounters the return
statement, it immediately exits the function, and no further code inside that function
is executed. If you don’t use a return statement, the function will return None by
default.
Example:
Imagine a simple vending machine function. You give it some money, and it returns a
snack to you.
Copy code
def vending_machine(money):
if money == 1:
ret urn "chips"
elif money == 2:
ret urn "soda"
else:
ret urn "Invalid amount "
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
If you give the vending machine 1 unit of money (money = = 1), it returns “chips”.
Copy code
snack = vending_machine(1)
print (snack) # Outputs: chips
In this example, you gave the vending_machine function 1 unit of money, and it
returned “chips” to you. The return statement in the function sent the value “chips”
back, which was then stored in the snack variable and printed out.
In simple terms, The return statement in Python functions is like getting an item back
after you’ve made a request. It sends a specific value from the function back to the
place where the function was called.
Q30. Can a f unct ion ret urn mult iple values? If so, how?
Yes, a function in Python can return multiple values. When it does, the values are
typically packed into a tuple and returned as a single tuple object. You can then
unpack these values into multiple variables when you call the function.
Example :
Let’s say you have a function that calculates both the quotient and remainder of
two numbers:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
When you call this function, it will return both the quotient and the remainder:
Copy code
result = divide_and_remainder(10, 3)
print (result ) # Outputs: (3, 1)
The function returned a tuple (3, 1), where 3 is the quotient and 1 is the remainder.
You can also unpack the returned values into separate variables:
Copy code
Here, quot holds the quotient, and rem holds the remainder.
In short, while a function technically returns a single object, by using tuples (or other
data structures like lists or dictionaries), you can effectively return multiple values
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
from a function and then unpack them as needed.
A recursive function is a function that calls itself in its definition. It’s a method used
in programming to solve problems by breaking them down into smaller and smaller
sub-problems until the sub-problem is simple enough to be solved directly.
Imagine you’re building a program to search for a specific file within a computer’s file
system. Directories can have files and other sub-directories inside them, and those
sub-directories can have their own files and further sub-directories, and so on. This
nested structure is inherently recursive.
If not, you’d then go into each sub-directory and repeat the process.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
In this scenario, the find_file function calls itself to dive into sub-directories, making
the problem manageable by breaking it down level by level.
In essence, recursive functions are particularly useful when the problem itself has a
recursive nature, like traversing tree structures, solving puzzles like the T ower of
Hanoi, or calculating factorials and Fibonacci sequences.
In Python, a decorator is a special type of function that allows you to add or modify
the behavior of another function or method without changing its source code. It’s
like wrapping a gift; the core gift remains the same, but the wrapping can change its
appearance or add some additional touches.
Scenario: Imagine you’re developing a web application, and you want to measure
the time it takes for certain functions to run, so you can identify any performance
bottlenecks.
Instead of adding timing code to every function you want to measure, you can use a
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
decorator to add this timing behavior.
Example:
Here’s a simple timer_decorator that measures and prints the time a function takes
to execute:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
import t ime
Output:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
In this scenario, the timer_decorator allows us to easily measure the execution time
of the process_data function (or any other function we decorate) without cluttering
its code with timing logic. Decorators provide a clean and reusable way to extend or
modify the behavior of functions or methods in Python.
Q33. How can you import a specif ic f unct ion f rom a module in Pyt hon?
Example :
Copy code
Q36. How do Pyt hon’s list comprehensions work under t he hood? Can you
provide an example where using a list comprehension would be more ef f icient
t han a t radit ional loop?
Creation of a New List: When a list comprehension is executed, Python creates a new
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
list in memory to store the results.
Iterating Over the Input Sequence: Python then iterates over the input sequence (or
sequences, in the case of nested comprehensions) f rom lef t to right.
Evaluation of the Expression: For each item in the input sequence, Python evaluates
the expression on the lef t side of the comprehension and appends the result to the new
list.
Return the New List: Once all items in the input sequence have been processed,
Python returns the new list.
Under the hood, list comprehensions are implemented using a loop, but they are
optimized in C (since Python is implemented in C), making them faster in many cases
than equivalent Python loops written out long-form.
Readability: For simple transf ormations and f iltering, list comprehensions can be more
concise and readable than traditional loops.
Example:
Let’s consider an example where we want to square all even numbers in a list:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
numbers = [1, 2, 3, 4, 5, 6]
squared_evens = []
f or num in numbers:
if num % 2 == 0:
squared_evens.append(num ** 2)
Copy code
In this example, the list comprehension is more concise and arguably more readable.
Additionally, the list comprehension avoids the overhead of the append method,
making it more efficient for large lists.
However, it’s essential to note that for more complex operations or when side
effects are required (like printing or updating other variables), traditional loops might
be more appropriate. Also, for very large datasets, generator expressions (using ()
instead of []) can be more memory-efficient than list comprehensions.
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 modif ies other code
at runtime (typically at startup).
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. T he unit testing f ramework of Python is known as unittest. It has similar f eatures with
unit testing f rameworks in other languages.
T est f ixture
T est case
T est suite
T est runner
Example:
Copy code
def xyz():
if __name__ == “__main__”:
Ans. Python sequences can be indexed as positive and negative numbers. A negative index
accesses elements f rom the end of the list counting backward.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q26. What is the dif f erence 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.
Example:
Copy code
a = range(1,10000)
print (t ype(a)
print (t ype(x))
Output:
<type ‘list’>
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
<type ‘xrange’>
Ans. A module is a Python object with arbitrarily named attributes that you can bind and
ref erence.
Ans. It is because a lambda f orm is used to make a new f unction object and then return at
runtime. Also, the syntactic f ramework of Python is unable to handle statements nested
inside expressions.
Ans. Flask (source code) is a Python micro web f ramework and it does not require particular
tools or libraries. It is used f or deploying python code into web apps.
Q30. How will you perf orm static analysis in a Python application or
f ind bugs?
Ans. PyChecker can be helpf ul as a static analyzer to identif y the bugs in the Python project.
T his also helps to f ind out the complexity-related bugs. Pylint is another tool that helps
check if the Python module is at par with the coding standards.
Thinking about whether you should learn Python and Hadoop or not? Check out the
top reasons to Learn Python and Hadoop.
Ans. Python Decorator is used to adjusting the f unctions in Python syntax quickly.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. T his is among the very commonly asked Python interview questions.
Python strings are immutable. Ironically, it is not a string, but a variable with a string value.
Ans. Pass stands f or no-operation Python statement. It means that pass is a null operation;
nothing happens when it is executed.
You might come across some conf using Python interview questions, MCQ is one of them,
but do not get stumped. You should be thorough with your study and be well prepared f or
the Python interview questions.
Always
Ans. Slicing is a computationally f ast way to methodically access a range of items f rom
sequence types like list, tuple, strings, etc.
Ans.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
list 1 = [5,4,3,2,1]
list 2 = list 1
list 2[0] = 0;
Output:
list1= : [5,4,3,2,1]
Ans. list.pop(obj=list[-1]) − Removes and returns last object f rom the list.
Ans. Python documentation strings (docstrings) provide an easy way to document Python
f unctions, modules, and classes.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code
x = T rue
y = False
z = False
if x or y and z:
print “HELLOWORLD”
else:
print “helloworld”
Ans. Output:
HELLOWORLD
Reason: Here, in Python AND operator has a higher pref erence than OR operator. So, (y
and z) are evaluated f irst.
Str
List
T uple
Unicode
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
byte array
xrange
buf f er
Ans. A Python set is an unordered collection of iterable and mutable data, and it has no
duplicate elements.
T ypeError
ValueError
NameError
IOError
IndexError
KeyError
Ans. T kinter is the de-f acto standard GUI (Graphical User Interf ace) package of Python.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
multiple threads.
Example:
Copy code
def mt ():
child.st art ()
Output:
MainT hread
Child T hread
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. T o capitalize the f irst letter of the string, capitalize() method is used. If the string is
already capitalized then it will return the original value.
Ans. len() is used to determine the length of an array, list and string in the program.
Example:
str1=’1234’
len(str1)
class Demo:
self .id = id
id = 777
acc = Acc(222)
print acc.id
Reason: “Demo” class automatically calls the method ”initl” and passes the object and “222”
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
is assigned to the object called id. So, the value “777” cannot be called and the output will be
“222”.
Ans. OS Module needs to be installed to delete any f ile. Af ter installing the module,
os.remove() f unction is used to delete a f ile.
Q53. Write a code to test whether the number is in the def ined
range or not?
Ans.
def test_range(n1):
if n1 in range(0, 555):
print(”%s is in range”%str(n1))
else:
Output:
test_range(555)
str=’XYZ ’
print(str.lower())
Output: xyz
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q55. What is the output of the f ollowing code?
print nameList[1][-1]
Ans. Output:
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.”
Ans. MySQL (Structured) and MongoDB (Unstructured) are supported by Python. First, the
modules should be imported to the library to interact with the database.
demoCodes = [1, 2, 3, 4]
demoCodes.append([5,6,7,8])
print len(demoCodes)
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’.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q59. Suppose a list1 is [2, 44, 191, 86], what would be the output f or
list1[-1]?
Ans. Output: 86
Explore the differences between Python and Java. Read our blog – Python Vs Java –
Which One is Better to Learn?
Ans. Generator f unctions help to declare a f unction that behaves like an iterator in a f ast,
easy, and neat way.
import datetime
now = datetime.datetime.now()
Ans. Yes, it is a case-sensitive language like other languages such as Java, C, and C++.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
list = [“2”, “7”, “3”, “5”, “1”]
list.sort()
print (list)
print(line.rstrip())
Ans. We can add elements to an array with the help of append(), insert (i,y) and extend()
f unctions.
Example:
x.append(3.3)
print(x)
x.extend([4.5,6.2,6.3])
print(x)
x.insert(2,3.8)
print(x)
Output:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
array(‘d’, [1.2, 2.2, 3.8, 3.2, 3.3, 4.5, 6.2, 6.3])
Example:
x=”Naukri learning”
print(x.split())
Ans. Classes are user-def ined which is def ined with a class keyword
Example:
Class Student:
S1 = Student (“xyz”)
print (S1.name)
Output: xyz
Ans. An empty class is a blank class that does not have any code def ined within its block.
We can create an empty class using the pass keyword.
Example:
Class x:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
 : pass
obj=x()
obj.name=”xyz”
Output:
Name = xyz
Q69. Explain the dif f erence 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 f aster program execution than a deep
copy.
Looking for top resources to learn Python? Read our blog – Why Learn Python?
Reasons and Top Resources to Learn Python
Ans. Pass statement is used if the statement is required syntactically, but no action is
required f or the program
Example:
If (x>20)
print(“Naukri”)
else
pass
Q71. What are the tools required to unit test your code?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. T o test units or classes, we can use the “unittest” python standard library. It is the
easiest way to test code, and the f eatures required are similar to the other unit testing tools
like T estNG, JUnit.
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])
Output:
[461]
Ans. T ernary operators are used to display conditional statements. T his consists of the
true or f alse values. Syntax :
Example: T he 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.
Q74. 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 f unction, or if
you want to pass a list or tuple of stored arguments to a f unction.
** kwargs is used when we don’t know how many keyword arguments to pass to a f unction,
or it is used to pass the values f rom a dictionary as the keyword argument.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
T he args and kwargs identif iers are a convention, you can also use * bob and ** billy but that
would not be wise
Ans. Python is an object-oriented programming language. T his 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.
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. T he Python interpreter can be used to
provide dynamic loading of conf iguration f iles and rebuild the interpreter.
Create a f ile with a name and in any language, which is compatible with your system compiler,
example, f ile.co f ile.cpp
Locate the f ile in the Modules / directory of the distribution you are using.
Add a line in the Setup.local f ile that is present in the Modules / directory.
Af ter successf ul execution of this rebuild, the interpreter uses the make command in the
top-level directory.
If the f ile is changed, then run rebuildMakef ile using command like ‘make Makef ile’.
Ans. We will use the f ollowing code to store an image locally f rom a URL
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
import urllib.request
Q78. How can you get the time (age) of the Google cache of any
URL or web page?
http://webcache.googleusercontent.com/search?q=cache:EL-URL-VA-HERE
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 – T o check the age of Unipython’s Google web cache, you would use the f ollowing
URL:
http://webcache.googleusercontent.com/search?q=cache:unipython.com
Ans. T he map f unction takes two arguments, one is iterable and another is a f unction and
applies the f unction to each element of the iterable. If the given f unction accepts more than
1 argument then many iterables are given.
import numpy as np
a = np.array ([1,2,3,4,5])
print (p)
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. Both NumPy and SciPy are modules of Python, and they are used f or various
operations of the data. NumPy stands f or Numerical Python while SciPy stands f or Scientif ic
Python. T he main dif f erences are –
NumPy SciPy
A collection of tools f or
Makes Python an alternative to MatLab, IDL, and Yorick Python, used f or general
numerical computing in Python
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 of f ers a host of high-quality 3D viewing f eatures,
using the powerf ul VT K engine.
Explore the concept of Data Science, read our post – what is Data Science?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. – Install Python f rom this link: https://www.python.org/downloads/
– Af ter that, install it on your PC. Find the location where Python has been installed on your
PC using the f ollowing command on the command line: cmd python
– Go to advanced system settings and add a new variable and name it PYT HON_NAME, and
paste the copied path
– Find the path variable, select its value and select ‘edit’
– Add a semicolon af ter the value if it is not present and then write% PYT HON_HOME%
Ans. Indentation is very important in Python. It specif ies a block of code. All the code within
classes, f unctions, loops, etc., is specif ied within an indented block. Generally, this is done
using f our space characters. If your code is not indented, it will not execute accurately and
will throw errors.
Ans. T he Self in Python is an instance or object of a class. It is explicitly included as the f irst
parameter. T his helps distinguish between methods and attributes of a class with local
variables.
T he variable self in the init method ref ers to the newly created object while in other methods;
it ref ers to the object whose method was called.
Ans. Break – It allows the termination of the loop when some condition is met and control is
transf erred to the next instruction.
Continue – T his lets you skip some part of a loop when a specif ic condition is met and
control is transf erred 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. T his is a null operation. Nothing happens when this runs.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q88. What are the iterators in Python?
Ans. Iterators in Python are objects used to iterate all the elements of a collection.
import random
random.random
Random instances can be made to display multithreading programs that create a distinct
instance of individual threads. T he other random generators used are:
randrange (a, b): choose an integer and def ine the range between [a, b). Returns elements by
randomly picking them f rom the specif ied range. It does not construct a range object.
Unif orm (a, b): select a f loating-point number that is def ined in the range of [a, b). It returns
the f loating-point number.
normalvariate (mean, sdev): used f or normal distribution where mu is mean and sdev is sigma
used f or standard deviation.
Ans. T his is one of those dif f icult Python interview questions to memorize at f irst, so give it
a f ew tries.
T he Dogpile ef f ect occurs when a website’s cache has expired and is hit by numerous
requests at the same time. T his causes a variety of problems, f rom increased large lag to
massive errors. A system called traf f ic light blocking is used to prevent the ef f ect of
Dogpiles.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q91. Explain what is encapsulation?
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
perf orm processes. T his is caused by a code error or some sof tware problem.
Ans. T his is one of the most dif f icult 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.
T his is because it works automatically, you won’t even notice.
Ans. Polymorphism is the ability to take many f orms, f or 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. T his contains its own parameters and variables. Polymorphism is allowed in Python.
Ans. It can be achieved in Python using abstract classes and interf aces. Data abstraction
only supplies the necessary details and hides the implementation.
Abstraction is selecting data f rom a larger pool to show only the relevant details to the
object.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Q96. Does Python use access specif iers?
Ans. Python does not have access modif iers. Rather it establishes the concept of pref ixing
the variable, method, or f unction name with a single or double underscore to mimic the
behavior of the private and protected access specif iers.
Ans. The bytes() function in Python returns a bytes object. It converts objects into
bytes objects. It also creates empty bytes objects of the specified size.
Ans. In Python, the ‘with statement’ is used for exception handling and resource
management. It makes the code cleaner and readable as it allows a file to be opened
and closed while executing a block of code containing the ‘with statement’.
Ans. Pandas is an open-source data analysis and manipulation tool built on top of the
Python programming language. It is a Python library that provides f ast and high-perf ormance
data structures and data analysis tools. It is widely used f or data science and machine
learning tasks.
Pandas is built on top of Numpy that of f ers f lexibility in creating data structures f or data
science, enabling you to create multidimensional, tabular, heterogeneous, data structures. It
also lets users perf orm data manipulation and time series. Python with Pandas is used in
dif f erent domains like analytics, f inance, economics, statistics, etc.
Also explore the commonly asked Data Science Interview Questions and Answers
Ans. Pandas Series is a one-dimensional array that can hold data of any type, like integer,
string, f loat, python objects. A Pandas Series is like a column in an excel sheet. It represents
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
a single column in memory, which can either belong to or be independent of a DataFrame.
Example:
T he below code will create a Series f rom ndarray. We will import a numpy module and use
array() f unction.
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
data = np.array([‘n’,’a’,’u’,’k’,’r’,’i’])
s = pd.Series(data)
print s
Output:
0 n
1 a
2 u
3 k
4 r
5 i
dtype: object
Ans. Pandas DataFrame is a two-dimensional tabular data structure with labeled axes. T he
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
data is aligned in a tabular manner in rows and columns. DataFrames are widely used in data
science, machine learning, scientif ic computing, etc.
2-dimensional
Size-mutable
Example:
T he below code will create a DataFrame using a single list or a list of lists.
# import pandas as pd
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print df
Output:
0 1
1 2
2 3
3 4
4 5
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Ans. We can combine DataFrames using the f ollowing f unctions:
pd.concat([data_frame1, data_frame2])
data_frame1.append(data_frame2)
join(): It is used to extract data f rom dif f erent DataFrames which have one or more
columns common.
data_frame1.join(data_frame2)
Ans. A namespace is a mapping f rom names to objects. It is a system that ensures that all
the object names in a program are unique and can be used without any conf lict. Python
maintains a namespace in the f orm of a Python dictionary. T hese namespaces are
implemented as dictionaries with ‘name as key’ mapped to its respective ‘object as value’.
Namespaces have dif f erent lif etimes as they are of ten created at dif f erent points in time.
Global Namespace – It consists of the names f rom various imported modules that are
being used in the ongoing project. T his namespace is created when the package is
imported into the script and lasts until the script ends.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Built-In Namespace – T his namespace contains built-in f unctions and built-in exception
names.
Ans. Inheritance is the capability of classes in Python to inherit the properties or attributes
of another class. A new class is def ined with little or no modif ication to an existing class.
T he new class is called derived or child class and the class f rom which it inherits is called the
base or parent class. Inheritance provides the code reusability f eature. It is transitive, which
means that if class B inherits f rom another class A, then all the subclasses of B would
automatically inherit f rom class A.
Multilevel Inheritance: Features of the base class and the derived class are f urther
inherited into the new derived class. A class inherits a superclass, and then another class
inherits the derived class f orming a ‘parent, child, and grandchild’ class structure.
Hierarchical inheritance: More than one derived class are created f rom a single base
class.
Ans. Literals ref er to the raw value or data given in a variable or constant. T hey represent a
f ixed value in the source code. In Python, there are various types of literals:
String literals
Numeric literals
Boolean literals
Literal Collections
Special literals
String Literals: T hese are created by enclosing text in single or double-quotes. T here
are two types of Strings Single-line and Multi-line String.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Example: “Literal” , ‘12345’
Integer:I=20
Float: i=3.6
Complex:2+7j
Boolean Literals: T here are two boolean literals – true and f alse.
Literal Collections: T here are f our dif f erent types of literal collections:
List literals
T uple literals
Set literals
Dict literals
Special Literals: Python supports one special literal i.e., None. None specif ies that f ield
that is not created.
f or i in range(0, n):
f or j in range(0, i + 1):
print(“* “, end=””)
print()
Output:
**
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
***
****
*****
Ans. Below is the code to check if the given number is palindrome or not:
num=input(“Enter a number:”)
if num==num[::-1]
else:
Output:
Case 1:
It is a Palindrome!
Case 2:
It is not a Palindrome!
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
list = [int(i) for i in list]
list.sort()
print (list)
Ans: In some cases, objects within the same scope have the same name. However, they
work dif f erently. In such cases, scope resolution help in Python automatically.
For Example:- Python modules namely ‘math’ and ‘cmath’ have a few function
names in common. Such as –
Copy code
log10()
Copy code
acos()
Copy code
exp(),
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
etc. T o resolve this ambiguity, it’s essential to pref ix each f unction with its respective
module, such as:
Copy code
mat h.exp()
and
Copy code
cmat h.exp()
Conclusion
We hope that this collection of the best python interview questions will help you prepare f or
your upcoming interview questions.
FAQs
What is Python?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
What are the key f eatures of Python.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.