0% found this document useful (0 votes)
67 views

Python Interview Questions From Shiksha

The document discusses Python interview questions, covering basic, intermediate and advanced questions. It provides examples of questions asked for different experience levels and by top companies. It also includes a section on system design questions and behavioral questions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Python Interview Questions From Shiksha

The document discusses Python interview questions, covering basic, intermediate and advanced questions. It provides examples of questions asked for different experience levels and by top companies. It also includes a section on system design questions and behavioral questions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Top 110+ Python Interview Questions and Answers

Atul Harsha
Senio r Manager Co ntent

Updated on Oct 11, 2023 18:15 IST


Python is a widely-used general-purpose, object-oriented, high-level programming
language. It is used to create web applications, and develop websites and GUI
applications. The popularity of the language is due to its versatility. In recent years,
the job opportunities for Python professionals have increased. In this article, we will
discuss python interview questions and answer.

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:

1. Int roduct ion (5 minut es)

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.

2. Basic Pyt hon Quest ions (10 minut es)

These questions would help gauge the candidate’s foundational knowledge of


Python.

What are the key dif f erences between Python 2 and Python 3?

Explain the dif f erence between a list and a tuple.

How does Python manage memory and garbage collection?

Describe the use of *args and **kwargs.

3. Int ermediat e Pyt hon Quest ions (15 minut es)

These questions dive deeper into Python’s features and libraries.

Explain the dif f erence between deepcopy and shallowcopy.

How would you implement caching in Python? (Expecting mentions of


f unctools.lru_cache or similar techniques)

Describe Python’s Global Interpreter Lock (GIL) and its implications.

How do you handle exceptions in Python? Can you provide an example?

4. Advanced Pyt hon Quest ions (15 minut es)

These questions target the candidate’s expertise and deep understanding of


Python.

How does Python’s asyncio work? Provide an example where it might be usef ul.

Describe Python’s descriptor protocol.

How would you optimize a Python application f or perf ormance?

Explain the dif f erence between new and init in Python’s class construction.

5. Pract ical Coding Exercise (30 minut es)

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.

6. Syst em Design (15 minut es)

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?

7. Behavioral Quest ions (10 minut es)

Many tech companies, values cultural fit and soft skills.


Describe a challenging problem you f aced in a previous project and how you overcame it.

How do you handle disagreements or conf licts in a team setting?

What attracts you to Microsof t and how do you see yourself contributing here?

8. Conclusion (5 minut es)

Allow the candidate to ask any questions they might have.

Explain the next steps in the interview process.

T hank the candidate f or their time.

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

Basic Python Question

Intermediate Python Question

Advance Python Question

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

SD2 Level Question

SD3 Level Question

SD4 Level Question

SD5 Level Question

System Design Question

Python Interview Questions asked in Top Companies

Company
Interview Question
Name

1. How would you implement a cache mechanism in Python to store the


Google
results of API calls?

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?

Amazon 3. How would you handle memory leaks in a Python application?

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?

Adobe 8. How would you implement a custom iterator in Python?

Oracle 9. Describe the dif f erences between a list, tuple, and set in Python.

10. How would you handle versioning in a Python-based microservices


Spotify
architecture?

11. Explain the concept of “list comprehensions” in Python. Provide an


T witter
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.
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?

14. Explain the dif f erences between “staticmethod”, “classmethod”, and


Dropbox
regular methods in Python.

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.

19. How would you handle real-time messaging in a Python-based


Slack
application?

20. Explain how Python’s “asyncio” works and how it can be used f or
T esla
asynchronous programming.

Basic Python Interview Questions and Answers

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?

Aspect Python 2 Python 3

Print Statement print “Hello, World!” print(“Hello, World!”)

Integer division (e.g., 5/2 =


Division T rue division (e.g., 5/2 = 2.5)
2)

Unicode Strings Implicitly treats as ASCII Strings are Unicode by def ault

xrange() and range() as


xrange() and range() range() behaves like xrange()
list

Input Function raw_input() input()

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

T ype Annotations No built-in support Built-in support f or type hints

Iterators and
itertools.izip() f or zipping zip() behaves like itertools.izip()
Iteration

Strings and byte strings Distinction between strings and


Byte Strings
similar byte literals

Standard Library
Library names may dif f er Some library reorganizations
Changes

Function Supports argument and return type


Not supported
Annotations annotations

Print as a Function print is a statement print is a f unction

Unicode Handling Basic Unicode support Improved Unicode support

Distinction between int All integers behave as long


Long Integers
and long integers

Integer division can be


Division Behavior Division always returns f loat
f orced

Exceptions Handling Less consistent chaining Consistent exception chaining

Syntax and Method Method name


Improved consistency and clarity
Changes inconsistencies

Python 2 reached end of Python 3 is the actively developed


End of Life
lif e in 2020 version

Learn more about Python, read our blog – what is Python?

Q2. Explain t he key f eat ures of Pyt hon.

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

Object-oriented: It is both procedure-oriented and object-oriented programming


language. In procedure-oriented languages, procedures can be used again. It allows

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.

Explore popular courses on Shiksha Online:

Free Python Interview Questions by Popular Data Structures and Algorithms


Great Learning Courses

Programming f or Everybody by University Google IT Automation with Python


of Michigan Prof essional Certif icate

T op Python Courses T op Free Python Courses

Must Read: Introduction to Python – Features, Use Cases, Resources, and Applications

Q3. What is t he dif f erence bet ween List and Tuple?

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

Mutability Mutable (can be changed) Immutable (cannot be changed)

Syntax my_list = [1, 2, 3] my_tuple = (1, 2, 3)

For collections of items that may For collections that should not
Use Case
change change

Elements can be added, removed, or Cannot modif y elements af ter


Modification
modif ied creation

Slightly slower than tuples due to Slightly f aster and memory-


Performance
added overhead f or mutation ef f icient

Hashable (can be used as


Not hashable (cannot be used as
Hashability dictionary keys or elements in
dictionary keys or elements in sets)
sets)

Parentheses Square brackets [] Parentheses ()

Similar iteration using loops or list


Iteration Similar iteration methods
comprehensions

Length Usually longer syntax: len(my_list) Shorter syntax: len(my_tuple)

Common append(), extend(), insert(),


Limited methods: count(), index()
Methods remove(), etc.

Immutability Used when data should be changed Used when data should remain
Use or updated constant

Examples names = [“Alice”, “Bob”, “Charlie”] coordinates = (10, 20)

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.

Q4. What is PEP 8?

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.

PEP 8 covers various aspects of code style, including indentation, naming


conventions, comments, and more. Following these guidelines not only makes your
code more pleasant to read but also helps maintain a unified style across projects.

Here’s a simple example to illustrate some PEP 8 principles:

Copy code

# PEP 8-compliant code

def calculat e_square(x):


"""Calculat e t he square of a number."""
ret urn x ** 2

class Person:
def __init __(self , name, age):
self .name = name
self .age = age

def greet (self ):


"""Greet t he person."""
print (f "Hello, my name is {self .name} and I am {self .age} years old.")

# Creating instances of the Person class


alice = Person("Alice", 30)
bob = Person("Bob", 25)

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.

Class Definitions: Class names are in CamelCase (Person).

Whitespace in Expressions and Statements: T here is proper spacing around


operators and af ter commas.

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

Clear, Natural Command


Flexible, multiple
Syntax & concise, language language,
ways to do the
Readability indentation- readability, suitable f or
same
based blocks clean syntax short scripts

Web dev, System admin,


T ext Web dev
data automation on
Versatility processing, (especially with
analysis, AI, Unix-like
system admin Rails)
etc. systems

Yes, with Yes, with many Yes, strong Limited to


Dynamic T yping optional type built-in data object-oriented strings and
hints types f eatures integers

Vast, Comprehensive, Command


Rich, especially
Standard Library “batteries- text processing execution, text
f or OOP
included” f ocus manipulation

Was popular in Active, Unix system


Community Large, active 90s, smaller especially administration
now around Rails f ocus

Interpreted, Interpreted, Interpreted,


Suitable f or
Perf ormance can be f ast text comparable to
short scripts
optimized processing Python

Cross-platf orm, Primarily f or


Platf orm Cross- Cross-platf orm,
some platf orm- Unix-like
Independence platf orm Unix f ocus
specif ic gems systems

“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

Q6. Explain memory management in Pyt hon.

To understand memory management in Python as imagine your computer’s memory


as a giant storage room. When you create something in Python, like a list or a 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.
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.

Python’s memory management is a combination of reference counting and garbage


collection. While reference counting handles most cases, the garbage collector
ensures that circular references don’t lead to memory leaks. This combination
ensures efficient memory management in Python applications.

Must Read: Memory Management in Python

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

Here, the module name is “arithmetic.”

Copy code

# This is the arithmetic module

def add(a, b):


ret urn a + b

def subt ract (a, b):


ret urn a - b

def mult iply(a, b):


ret urn a * b

def divide(a, b):


if b == 0:
ret urn "Cannot divide by zero!"
ret urn a / b

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.

Example usage in another script:

Copy code

import arit hmet ic

result = arit hmet ic.add(5, 3)


print (result ) # This will print 8

Python modules are used to break the large program into small segments that make the
code manageable and organized.

Modules serve several purposes:

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.

Some Built-in Modules in Python:

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.

datetime: Supplies classes f or manipulating dates and times.

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.

json: Allows encoding and decoding JSON data.

random: Contains f unctions to generate random numbers.

re: Provides f unctions f or working with regular expressions.

gc: Provides an interf ace to the garbage collection f acility of the Python interpreter.

urllib: Contains f unctions f or f etching data across the web.

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?

In Python, converting between strings and integers is straightforward using built-in


functions.
Converting a String to an Integer:
T o convert a string to an integer, you can use the int() f unction.

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

int _num = 123


st ring_num = st r(int _num)
print (st ring_num) # Outputs: "123"
print (t ype(st ring_num)) # Outputs: <class 'str'>

These conversions are commonly used in various scenarios, such as reading input
from users, processing data from files, or formatting output.

Read More: Data T ype in Python

Q9. How would you merge t wo dict ionaries?

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

dict 1 = {'a': 1, 'b': 2}


dict 2 = {'b': 3, 'c': 4}
dict 1.updat e(dict 2)
print (dict 1) # Outputs: {'a': 1, 'b': 3, 'c': 4}

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

Using the ** unpacking operator (Python 3.5+):


T his method creates a new dictionary without modif ying the original dictionaries.

Copy code

dict 1 = {'a': 1, 'b': 2}


dict 2 = {'b': 3, 'c': 4}
merged_dict = {**dict 1, **dict 2}
print (merged_dict ) # Outputs: {'a': 1, 'b': 3, 'c': 4}

Using the | merge operator (Python 3.9+):


T his is a new way introduced in Python 3.9 to merge dictionaries.

Copy code

dict 1 = {'a': 1, 'b': 2}


dict 2 = {'b': 3, 'c': 4}
merged_dict = dict 1 | dict 2
print (merged_dict ) # Outputs: {'a': 1, 'b': 3, 'c': 4}

Using the copy() method and update():


T his method creates a new dictionary without modif ying the original dictionaries.

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

dict 1 = {'a': 1, 'b': 2}


dict 2 = {'b': 3, 'c': 4}
merged_dict = dict 1.copy()
merged_dict .updat e(dict 2)
print (merged_dict ) # Outputs: {'a': 1, 'b': 3, 'c': 4}

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]

list 1.append([5, 6])


print (list 1) # Outputs: [1, 2, 3, 4, [5, 6]]

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]

list 1.ext end((6, 7))


print (list 1) # Outputs: [1, 2, 3, 4, 5, 6, 7]

list 1.ext end("89")


print (list 1) # Outputs: [1, 2, 3, 4, 5, 6, 7, '8', '9']

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.

Q11. How can you reverse a st ring in Pyt hon?

You can reverse a string in Python using slicing method.

Example:

Copy code

st ring = "Hello"
reversed_st ring = st ring[::-1]
print (reversed_st ring) # Outputs: "olleH"

Q12. What is st ring slicing? Provide an example.

String slicing is a technique in Python to extract a portion (or slice) of a string. It uses
the format:

Copy code

st ring[st art :st op:st ep]

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.

step: T he interval between characters in the slice. If omitted, it def aults to 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

st ring = "Pyt hon"


slice1 = st ring[1:4] # "yth"
slice2 = st ring[::2] # "Pto"
slice3 = st ring[-1:-4:-1] # "noh"

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

st ring = "Hello, World!"


subst ring = "World"

if subst ring in st ring:


print (f "'{subst ring}' exist s in '{st ring}'")
else:
print (f "'{subst ring}' does not exist in '{st ring}'")

Q14. What is a t uple? How is it dif f erent f rom a list ?

A tuple is an ordered collection of elements, similar to a list. However, unlike lists,


tuples are immutable, meaning their contents cannot be modified after they are
created. Tuples are defined by enclosing the elements in parentheses ().

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

my_t uple = (1, 2, 3, "Pyt hon")

How is a T uple it different from a list?

The primary differences between a tuple and a list are:


Mutability: Lists are mutable (can be modif ied), while tuples are immutable (cannot be
modif ied).

Syntax: Lists are def ined using square brackets [] , whereas tuples are def ined using
parentheses ().

Must Read: Understanding T uples in Python

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.

Q16. When would you use a t uple over a list ?

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

point _3D = (4, 5, 6)

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.

2. Using as Dictionary Keys:

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.

3. Function Multiple Returns:

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

def divide(a, b):


quot ient = a // b
remainder = a % b
ret urn quot ient , remainder

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.

4. Packing and Unpacking :

Tuples are often used for packing multiple values together and then unpacking them
elsewhere in the code.

Example : Swapping two values without a temporary variable.

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

colors = ('red', 'green', 'blue')


f or color in colors:
print (color)

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.

Q17. How can you remove duplicat es f rom 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.
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]

2. Using List Comprehension:

This method preserves the original order of the list.

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():

This method also preserves the original order of the 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

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:

This is a more traditional approach and preserves the original order.

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.

Q18. What is t he scope of a variable in Pyt hon?

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

def my_f unct ion():


local_variable = "I'm local"
print (local_variable)

my_f unct ion() # Outputs: "I'm local"

2. Enclosing (or Non-local) Scope :


T his scope is specif ic to nested f unctions.

If a variable is def ined in an enclosing f unction (a f unction containing another f unction),


the inner f unction has access to the variable, but it’s considered non-local to the inner
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

def out er_f unct ion():


enclosing_variable = "I'm enclosing"

def inner_f unct ion():


print (enclosing_variable)

inner_f unct ion()

out er_f unct ion() # Outputs: "I'm enclosing"

3. Global Scope :

A variable declared outside of all f unctions, methods, or classes has a global scope.

It is accessible throughout the module or f ile.

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

global_variable = "I'm global"

def my_f unct ion():


global global_variable
global_variable = "Modif ied global"
print (global_variable)

my_f unct ion() # Outputs: "Modified global"


print (global_variable) # Outputs: "Modified global"

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.).

T hese names are always available and don’t need to be imported.

Example :

Copy code

def my_f unct ion():


print (len([1, 2, 3])) # Using the built-in len() function

my_f unct ion() # Outputs: 3

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.

Aspect Local Variables Global Variables

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.

Exist only while the f unction is executing.


Exist f or the duration of the
Lifetime T hey are destroyed once the f unction
program’s execution.
exits.

Can be declared/modif ied inside


No specif ic keyword is required f or
Keyword a f unction using the global
declaration.
keyword.

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)

You can only use items inside a


Items in the garden or on the porch
room while you’re in that specif ic
Accessibility can be seen and used f rom any room
room. Once you leave, you can’t
with a window or door f acing them.
access them.

Items in a room (like a toy or T he garden gnome or the porch


book) are only available when the swing is always there, no matter
Lifetime
room is open. Once you lock the which room you’re in or even if all
room, they’re out of reach. rooms are locked.

If you want to change the color of


If you want to use an item f rom
the garden gnome, you can do it f rom
Intervention another room, you have to bring
any room, but you need to announce
it into your current room f irst.
(“declare”) you’re doing it.

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

# Global Variable (Garden gnome)


garden_gnome_color = "blue"

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.")

def kit chen():


# Local Variable (Item inside the kitchen)
mug_color = "green"
print (f "In t he kit chen, my mug is {mug_color}.")
print (f "From t he kit chen, I see a {garden_gnome_color} garden gnome.")

def paint _gnome(new_color):


global garden_gnome_color
garden_gnome_color = new_color
print (f "I've paint ed t he garden gnome {new_color}!")

# Let's see the house functions in action


bedroom()
kit chen()
paint _gnome("yellow")
bedroom()

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.

Must Read: Variables in Python

Q20. What is t he dif f erence bet ween Pyt hon Arrays and List s?

Aspect Python List Python Array (from array module)

A versatile and general-


purpose container that can A container that can store elements of a
Definition
store elements of mixed specif ic data type.
data types.

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.

Provides a wide range of Of f ers f ewer methods; mainly f ocused on


methods f or manipulation basic operations like append, pop, and
Functionality
(e.g., append, remove, array-specif ic ones like tofile and
insert). fromfile.

Generally consumes more


Memory Consumes less memory as it’s more size
memory due to f lexibility in
Consumption ef f icient f or a specif ic data type.
storing dif f erent data types.

Suitable when working with a large


Suitable f or general
amount of data of a single data type,
Use Case purposes where the data
especially when memory ef f iciency is a
type of elements can vary.
concern.

python import array my_array =


Example my_list = [1, “hello”, 3.14]
array.array(‘i’, [1, 2, 3, 4])

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.

Must Read: Lists in python

Must Read: Array manipulation using NumPy

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

def greet (name): # 'name' is a parameter


print (f "Hello, {name}!")

greet ("Alice") # "Alice" is an argument

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

def greet (name="Guest "):


print (f "Hello, {name}!")

greet () # Outputs: Hello, Guest!


greet ("Bob") # Outputs: Hello, Bob!

Must Read: Functions in Python

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

def display_inf o(name, age):


print (f "{name} is {age} years old.")

display_inf o("Charlie", 30) # Positional arguments


display_inf o(age=25, name="Eve") # Keyword arguments

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)

display_names("Anna", "Brian", "Cat herine")

def display_dat a(**dat a):


f or key, value in dat a.it ems():
print (f "{key}: {value}")

display_dat a(name="David", age=40, prof ession="Engineer")

In the first function, display_names, any number of positional arguments can be


passed, and they’ll be accessible as a tuple named names. In the second function,
display_data, any number of keyword arguments can be passed, and they’ll be
accessible as a dictionary named data.

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.")

order_scoops("vanilla", "chocolat e", "st rawberry")

**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

def build_sundae(**ingredient s):


print ("Building a cust om sundae wit h:")
f or ingredient , value in ingredient s.it ems():
print (f "{value} of {ingredient }")

build_sundae(vanilla="1 scoop", chocolat e="1 scoop", t opping="nut s", cherry="no cherry o

Difference between *args and **kwargs:

With *args, you’re just counting items (like scoops).


With **kwargs, you’re naming each item and giving it a value (like building a custom
sundae).
So, when you think of *args and **kwargs, think of scoops of ice cream vs. building a
sundae!

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.

Q26. What is a Lambda Funct ion in Pyt hon?

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.

Example in Python : Instead of defining a function in the standard way:

Copy code

def add(x, y):


ret urn x + y

You can use a lambda function for the same purpose:

Copy code

add = lambda x, y: x + y

Q27. How would you writ e a lambda f unct ion t o square a number?

A lambda function to square a number can be written as:

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

square = lambda x: x**2

This lambda function can be used as:

Copy code

print (square(5)) # Outputs: 25

Q28. Can lambda f unct ions have mult iple input s? If so, provide an example.

Yes, lambda functions can have multiple inputs.

Example : A lambda function to add two numbers:

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

Must Read: Lambda Function in Python

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 "

Here’s how it works:

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”.

If you give it 2 units of money (money = = 2), it returns “soda”.

For any other amount, it returns “Invalid amount”.

Now, when you use this function:

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

def divide_and_remainder(a, b):


quot ient = a // b
remainder = a % b
ret urn quot ient , remainder

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

quot , rem = divide_and_remainder(10, 3)


print (quot ) # Outputs: 3
print (rem) # Outputs: 1

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.

Q31. What are recursive f unct ions? Why do we use it ?

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.

Scenario: File System Search

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.

To search for a file, you’d:

Look at the current directory’s f iles.

If you f ind the f ile, great!

If not, you’d then go into each sub-directory and repeat the process.

This is a natural fit for a recursive approach. Here’s a simplified 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 f ind_f ile(t arget , current _direct ory):


f or it em in current _direct ory:
if it em is a f ile:
if it em.name == t arget :
ret urn it em.pat h
elif it em is a direct ory:
# Recursively search in t he sub-direct ory
pat h = f ind_f ile(t arget , it em)
if pat h:
ret urn pat h

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.

Q32. What is a decorat or in Pyt hon? Provide an example of a simple decorat or


wit h a scenario. based example.

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

# This is the decorator function


def t imer_decorat or(f unc):
def wrapper(*args, **kwargs):
st art _t ime = t ime.t ime()

result = f unc(*args, **kwargs) # Call the original function

end_t ime = t ime.t ime()


elapsed_t ime = end_t ime - st art _t ime
print (f "{f unc.__name__} t ook {elapsed_t ime:.2f } seconds t o run.")

ret urn result


ret urn wrapper

# Applying the decorator to a function using the "@" syntax


@t imer_decorat or
def process_dat a(dat a):
t ime.sleep(2) # Simulating some data processing that takes 2 seconds
print (f "Processed {len(dat a)} it ems.")

# Calling the decorated function


process_dat a(list (range(1000)))

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

Processed 1000 it ems.


process_dat a t ook 2.00 seconds t o run.

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.

Must Read: Python Decorators

Q33. How can you import a specif ic f unct ion f rom a module in Pyt hon?

Answer : You can use the from … import … statement.

Example :

Copy code

# Assuming there's a function called 'my_function' in a module named 'my_module'


f rom my_module import my_f unct ion

Intermediate Python Interview Question

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?

Ans: How List Comprehensions Work Under the Hood:

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.

Condition Evaluation: If there’s a conditional in the comprehension (using if ), Python


checks it f or each item. If the condition is T rue, the item is processed; otherwise, it’s
skipped.

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.

Efficiency of List Comprehensions:

List comprehensions can be more efficient than traditional loops in several


scenarios:
Memory Usage: List comprehensions can be more memory-ef f icient because they
generate the output list in one go, without the need f or intermediate storage or append
operations.

Speed: Due to their optimization in C, list comprehensions can be f aster than


equivalent f or-loops in Python, especially f or simple operations.

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:

Using a traditional loop :

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)

Using a list comprehension :

Copy code

squared_evens = [num ** 2 f or num in numbers if num % 2 == 0]

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.

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 modif ies other code
at runtime (typically at startup).

Q24. What is a unittest?

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.

Unittest supports some important concepts of object-oriented Programming:

T est f ixture

T est case

T est suite

T est runner

Example:

Copy code

import unit t est

class ABC(unit t est .T est Case):

def xyz():

if __name__ == “__main__”:

unit t est .main()

Q25. What is a negative index?

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)

# initializing a with xrange()

x = xrange(1,10000 t est ing t he t ype of a

i (“T he ret urn t ype of range() is : “)

print (t ype(a)

# testing the type of x

print (“T he ret urn t ype of xrange() is : “)

print (t ype(x))

Output:

T he return type of range() is :

<type ‘list’>

T he return type of xrange() is :

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’>

Q27. Def ine module and package.

Ans. A module is a Python object with arbitrarily named attributes that you can bind and
ref erence.

A Python package is simply a directory of Python module(s).

Q28. Why don’t lambda f orms have statements?

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.

Q29. What is Flask?

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.

Must Check: Python Flask Online Courses and Certif ications

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.

Q31.When will you use the Python Decorator?

Ans. Python Decorator is used to adjusting the f unctions in Python syntax quickly.

Q32. Are Python strings immutable or mutable?

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.

Q33. What is a pass in Python?

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.

Must Read: Pass Statement in Python

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

Always

Ans. c) when no exception occurs

Q35. What is slicing?

Ans. Slicing is a computationally f ast way to methodically access a range of items f rom
sequence types like list, tuple, strings, etc.

Must Read: Slicing in Python

Q36. What is the output of the f ollowing code?

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;

print “list 1= : “, list 1

Output:

list1= : [5,4,3,2,1]

Q37. How is the last object f rom a list removed?

Ans. list.pop(obj=list[-1]) − Removes and returns last object f rom the list.

Q38. What is docstring?

Ans. Python documentation strings (docstrings) provide an easy way to document Python
f unctions, modules, and classes.

Q39. How to delete a f ile?

Ans. We can delete a f ile in Python by using a command os.remove (f ilename) or


os.unlink(f ilename).

Q40. What is the output of the f ollowing 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

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.

Q41. How many kinds of sequences does Python support? Name


them.

Ans. Python supports seven sequence types –

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

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 Python set is an unordered collection of iterable and mutable data, and it has no
duplicate elements.

Must Read: Sets in Python

Q44. Name some standard Python errors.

Ans. Some standard errors are –

T ypeError

ValueError

NameError

IOError

IndexError

KeyError

We can use dir(__builtin__) to list all the errors.

Q45. What is Tkinter?

Ans. T kinter is the de-f acto standard GUI (Graphical User Interf ace) package of Python.

Q46. What is Multithreading?

Ans. Multithreading stands f or running a number of programs simultaneously by invoking

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

f rom t hreading import *

print (current _t hread().get Name())

def mt ():

print (“Child T hread”)

child=T hread(t arget =mt )

child.st art ()

print (“Execut ing t hread name :”,current _t hread().get Name())

Output:

MainT hread

Child T hread

Executing thread name : MainT hread

Q47. How is a list reversed?

Ans. T o reverse lists, one can use list.reverse()

Q48. How to capitalize the f irst letter of 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.
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.

Q49. Which python library is used f or Machine learning?

Ans. Scikit-learn python Library is used f or Machine learning.

Must Read: T op 10 python libraries f or Data Science and 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.

Example:

str1=’1234’

len(str1)

Popular Python Course Providers:

T op Python Courses by Udemy Popular Python Courses by Coursera

T op Python Courses by Udacity Popular Python Courses by PluralSight

Q51. What is the output of the f ollowing code?

class Demo:

def __initl__(self , id):

self .id = id

id = 777

acc = Acc(222)

print acc.id

Ans. Output: 222

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”.

Q52. How to delete a f ile in Python?

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:

print(”%s is not in range”%str(n1))

Output:

test_range(555)

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

str=’XYZ ’

print(str.lower())

Output: xyz

Must Read: Strings 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.
Q55. What is the output of the f ollowing code?

nameList = [‘Joe’, ‘Nick’, ‘Bob’, ‘Harry’]

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.”

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 f ollowing code?

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’.

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”)

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

List1[-1] shows the last integer of the list

Q60. What is the maximum length of an identif ier?

Ans. T he maximum possible length of an identif ier in python is 79 characters.

Explore the differences between Python and Java. Read our blog – Python Vs Java –
Which One is Better to Learn?

Q61. Can you tell me the generator f unctions in Python?

Ans. Generator f unctions help to declare a f unction that behaves like an iterator in a f ast,
easy, and neat way.

Q62. Write a code to display the current time.

Ans. Here is the code to represent the current time:

import datetime

now = datetime.datetime.now()

print (“Current date and time : “)

print (now.stgf time(“%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. T o sort a numerical list, use the f ollowing 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.
list = [“2”, “7”, “3”, “5”, “1”]

list = [int(i) f or i in list]

list.sort()

print (list)

Q64. Write a code to display the contents of a f ile in reverse.

Ans. T o reverse the content, use the f ollowing code:

f or line in reversed(list(open(f ilename.txt))):

print(line.rstrip())

Q65. 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()
f unctions.

Example:

x=arr.array(‘d’, [1.2 , 2.2 ,3.2] )

x.append(3.3)

print(x)

x.extend([4.5,6.2,6.3])

print(x)

x.insert(2,3.8)

print(x)

Output:

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])

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])

Q66. Why is the split used in Python?

Ans. T he split() method is used to separate two strings.

Example:

x=”Naukri learning”

print(x.split())

Output: [‘Naukri’, ‘learning’]

Q67. How to create classes in Python?

Ans. Classes are user-def ined which is def ined with a class keyword

Example:

Class Student:

def _init_(self , name) :

self .name = name

S1 = Student (“xyz”)

print (S1.name)

Output: xyz

Must Read: Classes and Objects in Python

Q68. How do we create an empty class?

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.
&nbsp: pass

obj=x()

obj.name=”xyz”

print (“Name = “,obj.name)

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

Q70. Which statement can we use if the statement is required


syntactically, but no action is needed f or the program?

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.

Q72. 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])

Output:

[461]

Must Check: NumPy Interview Question

Q73. How can you use ternary operators (Ternary) in Python?

Ans. T ernary operators are used to display conditional statements. T his consists of the
true or f alse values. Syntax :

T he ternary operator is indicated as:

[on_true] if [expression] else [on_f alse] x, y = 25, 50big = x if x <y else y

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

Q75. Does Python have OOps concepts?

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.

Must Read: OOPs Concept in Python

Q76. What are 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. T he Python interpreter can be used to
provide dynamic loading of conf iguration f iles and rebuild the interpreter.

For this, the steps required in the process are:

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.

Run the f ile using spam f ile.o

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’.

Q77. How do I save an image locally using Python whose URL I


already know?

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

urllib.request.urlretrieve (“URL”, “f ile-name.jpg”)

Q78. How can you get the time (age) of the Google cache of any
URL or web page?

Ans. Using the f ollowing URL f ormat:

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

Q79. What is the map f unction in Python?

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.

Check out the best Python Courses online

Q80. How are percentages calculated with Python / NumPy?

Ans. Percentages can be calculated using the f ollowing code:

import numpy as np

a = np.array ([1,2,3,4,5])

p = np.percentile (a, 50) #Returns 50%.

print (p)

Q81. What is the dif f erence between NumPy and SciPy?

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

Support operations like


Used f or ef f icient operation on homogeneous data
integration, dif f erentiation,
that are stored in arrays
gradient optimization, etc.

Multi-dimensional array of objects, used f or basic No related array or list


operations such as sorting, indexing, and elementary concepts as it is more
f unctioning on the array data type f unctional

Suitable f or computation of data and statistics, and Suitable f or complex computing


basic mathematical calculation of numerical data

Q82. 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 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?

Q83. What is PYTHONPATH?

Ans. It is an environment variable and is used when importing a module. In addition,


PYT HONPAT H is used to check the presence of imported modules in some directories. T he
interpreter uses it to determine which module to load.

Q84. How to install Python on Windows and set a path variable?

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%

Q85. Is indentation required in Python?

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.

Q86. What is the Self in Python?

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.

Q87. How does break, continue and pass work?

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.

Q89. How can you generate random numbers in Python?

Ans. T he random module is the standard module f or generating a random number. T he


method is def ined as:

import random

random.random

T he random.random () declaration returns the f loating-point number that is in the range of


[0, 1]. T he f unction generates random f loating numbers. T he 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. 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.

Q90. What is the Dogpile ef f ect?

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. 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 f unctions.

Q92. 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
perf orm processes. T his is caused by a code error or some sof tware problem.

Q93. Does the Python language have a compiler?

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.

Q94. What is polymorphism in Python?

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.

Q95. How is data abstraction done 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.

Must Read: Abstraction 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.
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.

Q97. Explain the bytes() f unction in Python.

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.

Q98. Explain the ‘with statement’.

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’.

Q99. What is Pandas?

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

Q100. What is a Pandas Series?

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.

We can create a Pandas Series using the below constructor −

pandas.Series( data, index, dtype, copy)

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

Q101. What are Pandas DataFrames?

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.

Here are some f eatures of Dataf rames:

2-dimensional

Labeled axes (rows and columns)

Size-mutable

Arithmetic operations can be perf ormed on rows and columns

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

Must Read: Series vs DataFrame in Pandas

Q102. How to combine DataFrames in Pandas?

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:

concat() function: It is used f or vertical stacking.

pd.concat([data_frame1, data_frame2])

append(): It is used f or horizontal stacking of DataDrames.

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)

Must Read: Adding Columns to Pandas DataFrame

Q103. How to access the top n rows of a dataf rame?

Ans. To access the top n rows of a dataframe, we will use df.head(n).

Q104. How to access the last n rows of a dataf rame?

Ans. We will use df.tail(n) to access the last n rows of a dataframe

Q105. What are Python namespaces?

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.

Some of the namespaces in a Python program are:

Local Namespace – it contains local names inside a f unction. T he local namespace is


created f or a f unction call and lasts until the f unction returns.

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.

Q106. What is Inheritance in Python?

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.

Python supports the f ollowing types of inheritance:

Single Inheritance: A class inherits only one superclass.

Multiple Inheritance: A class inherits multiple superclasses.

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.

Q107. What are Python literals?

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’

Numeric Literals: T hey support three types of literals:

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.

Must Read: Literals in Python

Q108. Write a Python program to produce half pyramid using *.

Ans. Below is the code to print half pyramid using *

n = int(input(“Enter the number of rows”))

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.
***

****

*****

Q109. Write a python program to check if the number given is a


palindrome or not

Ans. Below is the code to check if the given number is palindrome or not:

num=input(“Enter a number:”)

if num==num[::-1]

print (“It is a Palindrome!”)

else:

print(“It is not a Palindrome!”)

Output:

Case 1:

Enter a number: 12321

It is a Palindrome!

Case 2:

Enter number: 5678

It is not a Palindrome!

Must Read: Palindrome in Python

Q110. Write a sorting algorithm f or a numerical dataset in Python.

Ans. Below is the sorting algorithm for a numerical dataset in Python

list = [“9”, “5”, “2”, “0”, “8”]

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)

Q111. Explain how can you make a Python Script executable on


Unix?

Ans: Python Script file must begin with # !/usr/bin/env python

Q112. What is Scope Resolution in Python?

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.

T op T rending T ech Articles:


Career Opportunities af ter BT ech | Online Python Compiler | What is Coding | Queue Data
Structure | T op Programming Language | T rending DevOps T ools | Highest Paid IT Jobs |
Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux
Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us


what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

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.

What are the top 10 python interview questions?

How to prepare f or interview question?

What is OOPS in Python?

What is data type in Python?

What is lambda in Python?

What is a Python Decorator?

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 might also like