Python Book
Python Book
AN EDTECH COMPANY
HOW TO CRACK
PYTHON
INTERVIEW
PYTHON INTERVIW QUESTION
1. What is Python, and list some of its key
features.
Python is a versatile, high-level programming
language known for its easy-to-read syntax and
broad applications. Here are some of Python’s
key features:
Simple and Readable Syntax: Python’s
syntax is clear and straightforward, making
it accessible for beginners and efficient for
experienced developers.
Interpreted Language: Python executes code
GROWAI
line by line, which helps in debugging and
testing.
Dynamic Typing: Python does not require
explicit data type declarations, allowing
more flexibility.
Extensive Libraries and Frameworks:
Libraries like NumPy, Pandas, and Django
expand Python’s functionality for specialized
tasks in data science, web development, and
more.
PYTHON INTERVIW QUESTION
Cross-Platform Compatibility: Python can
run on different operating systems, including
Windows, macOS, and Linux.
GROWAI
Memory Usage: Consumes more memory.
Performance: Slower iteration compared to
tuples but better for insertion and deletion
operations.
Methods: Offers various built-in methods for
manipulation.
Example:
PYTHON INTERVIW QUESTION
Tuple:
Immutable: Elements cannot be changed
after creation.
Memory Usage: Consumes less memory.
Performance: Faster iteration compared to
lists but lacks the flexibility of lists.
Methods: Limited built-in methods.
Example:
GROWAI
3. What is __init__() in Python?
The __init__() method is known as a constructor
in object-oriented programming (OOP)
terminology. It is used to initialize an object's
state when it is created. This method is
automatically called when a new instance of a
class is instantiated.
Purpose:
Assign values to object properties.
Perform any initialization operations.
PYTHON INTERVIW QUESTION
Example:
We have created a book_shop class and added
the constructor and book() function. The
constructor will store the book title name and
the book() function will print the book name.
To test our code we have initialized the b object
with “Sandman” and executed the book()
function.
GROWAI
PYTHON INTERVIW QUESTION
4. What is the difference between a mutable
data type and an immutable data type?
GROWAI
Example:
PYTHON INTERVIW QUESTION
Immutable data types:
Definition: Immutable data types are those
that cannot be modified after their creation.
Examples: Numeric (int, float), String, Tuple.
Characteristics: Elements cannot be changed
once set; any operation that appears to
modify an immutable object will create a
new object.
Example:
GROWAI
PYTHON INTERVIW QUESTION
5. Explain list, dictionary, and tuple
comprehension with an example.
List
List comprehension offers one-liner syntax to
create a new list based on the values of the
existing list. You can use a for loop to replicate
the same thing, but it will require you to write
multiple lines, and sometimes it can get
complex.
GROWAI
List comprehension eases the creation of the list
based on existing iterable.
Dictionary
Tuple
GROWAI
You can run the loop to extract the elements or
convert them to a list.
PYTHON INTERVIW QUESTION
6. Can you explain common searching and
graph traversal algorithms in Python?
GROWAI
search range in half until the target is
found.
AVL Tree: An AVL tree keeps things
balanced, which is a big advantage if you’re
frequently inserting or deleting items in a
tree. This self-balancing binary search tree
structure keeps searches fast by making
sure the tree never gets too skewed.
PYTHON INTERVIW QUESTION
Breadth-First Search (BFS): BFS is all about
exploring a graph level by level. It’s especially
useful if you’re trying to find the shortest path
in an unweighted graph since it checks all
possible moves from each node before going
deeper.
Depth-First Search (DFS): DFS takes a
different approach by exploring as far as it
can down each branch before backtracking.
It’s great for tasks like maze-solving or tree
traversal.
GROWAI
A Algorithm*: The A* algorithm is a bit more
advanced and combines the best of both BFS
and DFS by using heuristics to find the
shortest path efficiently. It’s commonly used in
pathfinding for maps and games.
PYTHON INTERVIW QUESTION
7. What is a KeyError in Python, and how can
you handle it?
GROWAI
dictionary, you’ll get a KeyError. To handle this
error, you have a few options:
GROWAI
Garbage collection in Python uses reference
counting as well as a cyclic garbage collector to
detect and collect unused data. When an object
has no more references, it becomes eligible for
garbage collection. The gc module in Python
allows you to interact with the garbage collector
directly, providing functions to enable or disable
garbage collection, as well as to perform manual
collection.
PYTHON INTERVIW QUESTION
9. What is the difference between shallow copy
and deep copy in Python, and when would you
use each?
GROWAI
contains other mutable objects (like lists within
lists), the shallow copy will reference the same
inner objects. This can lead to unexpected
changes if you modify one of those inner
objects in either the original or copied
structure. You can create a shallow copy using
the copy() method or the copy module’s copy()
function.
Deep Copy: A deep copy creates a new object
and recursively copies all objects found within
the original.
PYTHON INTERVIW QUESTION
This means that even nested structures get
duplicated, so changes in one copy don’t affect the
other. To create a deep copy, you can use the
copy module’s deepcopy() function.
GROWAI
Python Copy List: What You Should Know
tutorial to learn more. This tutorial includes a
whole section on the difference between shallow
copy and deep copy.
GROWAI
Instead of displaying patch() is being called, it
has displayed monk_p() is being called.
PYTHON INTERVIW QUESTION
11. What is the Python “with” statement
designed for?
The with statement is used for exception handling
to make code cleaner and simpler. It is generally
used for the management of common resources
like creating, editing, and saving a file.
Example:
Instead of writing multiple lines of open, try,
finally, and close, you can create and write a text
file using the with statement. It is simple.
GROWAI
12. Why use else in try/except construct in
Python?
GROWAI
Division is successful.
PYTHON INTERVIW QUESTION
13. What are decorators in Python?
Example:
GROWAI
PYTHON INTERVIW QUESTION
14. What are context managers in Python, and
how are they implemented?
Example:
GROWAI
PYTHON INTERVIW QUESTION
15. Given a positive integer num, write a
function that returns True if num is a perfect
square else False.
GROWAI
3. Returning the result as a boolean.
Test 1
We have provided number 10 to the
valid_square() function.
GROWAI
PYTHON INTERVIW QUESTION
16. Given an integer n, return the number of
trailing zeroes in n factorial n!
To pass this challenge, you have to first calculate
n factorial (n!) and then calculate the number of
training zeros.
Finding factorial
In the first step, we will use a while loop to iterate
over the n factorial and stop when the n is equal
to 1.
Calculating trailing zeros
In the second step, we will calculate the trailing
GROWAI
zero, not the total number of zeros. There is a
huge difference.
GROWAI
PYTHON INTERVIW QUESTION
17. Can you find the maximum single sell profit?
GROWAI
= 4, and sell = 20. Maximizing the profit.
Solution:
We will calculate the global profit by
subtracting global sell (the first element in the
list) from current buy (the second element in
the list).
PYTHON INTERVIW QUESTION
Run the loop for the range of 1 to the length
of the list.
Within the loop, calculate the current profit
using list elements and current buy value.
If the current profit is greater than the global
profit, change the global profit with the
current profit and global sell to the i element
of the list.
If the current buy is greater than the current
element of the list, change the current buy
with the current element of the list.
GROWAI
In the end, we will return global buy and sell
value. To get global buy value, we will subtract
global sell from global profit.
GROWAI
PYTHON INTERVIW QUESTION
18. How will you check if a class is a child of
another class?
This is done by using a method called issubclass()
provided by python. The method tells us if any
class is a child of another class by returning true
or false accordingly.
For example:
GROWAI
We can check if an object is an instance of a
class by making use of isinstance() method:
PYTHON INTERVIW QUESTION
19. What is init method in python?
The init method works similarly to the
constructors in Java. The method is run as soon
as an object is instantiated. It is useful for
initializing any attributes or default behaviour of
the object at the time of instantiation.
For example:
GROWAI
20. Why is finalize used?
GROWAI
Look at the below example
PYTHON INTERVIW QUESTION
22. What is mutable and immutable
objects/data types in Python?
Mutation generally refers to 'change'. So when we
say that an object is mutable or immutable we
meant to say that the value of object can/cannot
change.
When an object is created in Python, it is assigned
a type and an id. An object/data type is mutable
if with the same id, the value of the object
changes after the object is created.
GROWAI
Mutable objects in Python -- Objects that can
change after creation. Lists, byte arrays, sets, and
dictionaries.
PYTHON INTERVIW QUESTION
Immutable objects in Python -- Numeric data
types, strings, bytes, frozen sets, and tuples.
GROWAI
PYTHON INTERVIW QUESTION
23. What is the difference between list and
tuples in Python?
GROWAI
Tuple does not allot any extra memory during construction
because it will be immutable so does not have to worry about
addition of elements.
Reusablity
Tuple literally assigns the same object to the new variable
while list basically copies all the elements of the existing list.
GROWAI
PYTHON INTERVIW QUESTION
GROWAI
object 17. Once the object reference count reaches 0, object is
removed from memory.
The reference count
increases if an object is assigned a new name or is placed
in a container, like tuple or dictionary.
decreases when the object's reference goes out of scope or
when name is assigned to another object. Python's garbage
collector handles the job of removing objects & a
programmer need not to worry about allocating/de-
allocating memory like it is done in C.
PYTHON INTERVIW QUESTION
GROWAI
Examples :- TypeError, ValueError, ImportError, KeyError,
IndexError, NameError, PermissionError, EOFError,
ZeroDivisionError, StopIteration
GROWAI
28. Explain Generators and use case of it.
A function or method which uses the yield statement is called
a generator function. Such a function, when called, always
returns an iterator object which can be used to execute the
body of the function: calling the iterator’s
iterator._next_()method will cause the function to execute until
it provides a value using the yield statement.
When the function executes a return statement or falls off the
end, a StopIteration exception is raised and the iterator will
have reached the end of the set of values to be returned. Note
that a generator can have n numbers of yield statements
PYTHON INTERVIW QUESTION
Use Case
Generators are good for calculating large sets of results where
you don't know if you are going to need all results, or where
you don't want to allocate the memory for all results at the
same time.
Note: You can only iterate over a generator once, if you try to
GROWAI
loop over it second time it will return nothing. Generators also
do not store all the values in memory, they generate the values
on the fly
GROWAI
Objects are data with methods attached, closures are
functions with data attached.
PYTHON INTERVIW QUESTION
31. How to make a chain of function decorators?
GROWAI
32. Three different ways to fetch every 3rd item of a list
GROWAI
GROWAI
directly.
PYTHON INTERVIW QUESTION
34. What's the difference between a Python module and a
Python package?
Module
The module is a Python file that contains collections of
functions and global variables and with having a .py extension
file.
Package
The package is a directory having collections of modules. This
directory contains Python modules and also having init.py file
by which the interpreter interprets it as a Package.
GROWAI
List comprehensions are generally faster than 'a for loop'
because of the implementation of both. One key difference is
that 'for loop' generally rounds up more than one
statement/operation as compared to 'list comprehension' which
has to perform single operation on all the elements. For
example, creating a list or update in an existing list is faster
when done using list comprehension.
PYTHON INTERVIW QUESTION
34. Explain Meta Classes in Python.
GROWAI
Meta Class call
The metaclass is called with the
name: name of the class,
bases: tuple of the parent class (for inheritance, can be
empty) and
attributes: dictionary containing attributes names and
values.
PYTHON INTERVIW QUESTION
GROWAI
36. Explain object creation process in detail. Which method
is called first?
GROWAI
38. Difference between an expression and a statement in
Python
GROWAI
using different number of arguments.
PYTHON INTERVIW QUESTION
41. What can be used as keys in dictionary?
GROWAI
42. Explain shallow and deep copy in Python
GROWAI
original.
.pyc files are created by the Python interpreter when a .py file
is imported, and they contain the "compiled bytecode" of the
imported module/program, the idea being that the "translation"
from source code to bytecode (which only needs to be done
once) can be skipped on subsequent imports if the .pyc is
newer than the corresponding .py file, thus speeding startup a
little. But it's still interpreted.
PYTHON INTERVIW QUESTION
43. How private varibles are declared in Python?
GROWAI
45. How do you define a dict where several keys has same
value?
PYTHON INTERVIW QUESTION
46. What are different types of namespaces in Python?
Types of Namespaces
GROWAI
function returns or raises an exception that is not handled
within the function.
Global Namespace: The global namespace for a module is
created when the module definition is read in; normally,
module namespaces also last until the interpreter quits.
Built-in Namespace: The namespace containing the built-in
names is created when the Python interpreter starts up,
and is never deleted.
PYTHON INTERVIW QUESTION
47. How can you access attribute of parent class bypassing
the attribute with the same name in derived class?
GROWAI
is returned; otherwise, y is evaluated and the resulting
value is returned.
PYTHON INTERVIW QUESTION
49. Difference between multiprocessing and multithreading
GROWAI
than have your CPU sit idly by.
GROWAI
52. Example filter with lambda expression.
filter
55. What will be the datatype of the var in the below code
snippet?
GROWAI
1. str and int
2. int and int
3. str and str
4. int and str [ANSWER]
GROWAI
1. 15 [ANSWER]
2. 0
3. 20
4. None of these
1. for
2. while
3. do-while
4. None of the above
PYTHON INTERVIW QUESTION
57. What will be the output of the following code snippet?
GROWAI
1. 15 [ANSWER]
2. 0
3. 20
4. None of these
1. for
2. while
3. do-while [ANSWER]
4. None of the above
PYTHON INTERVIW QUESTION
60. What will be the output of the following code snippet?
1. Error
2. [1, 2]
3. [1, 2, 1, 2]
4. [1, 2, 1, 2, 1, 2] [ANSWER]
GROWAI
2. ['Sunday', 'Monday', 'Wednesday'] [ANSWER]
3. ['Monday', 'Tuesday', 'Wednesday']
4. ['Sunday', 'Monday', 'Tuesday']
1. if ele in list
2. if not ele not in list
3. Both A and B [ANSWER]
4. None of the above
PYTHON INTERVIW QUESTION
63. What will be the type of the variable sorted_numbers in
the below code snippet?
1. List [ANSWER]
2. Tuple
3. String
4. Int
GROWAI
1. filter [ANSWER]
2. int
3. list
4. tuple
GROWAI
1. [7, 19, 45, 89] [ANSWER]
2. [2, 4, 22, 72]
3. [4, 7, 19, 2, 89, 45,72, 22]
4. [2, 4, 7, 19, 22, 45, 72, 89]
1. Even [ANSWER]
2. Odd
3. Error
4. None
GROWAI
1. 54 is an even number [ANSWER]
2. 54 is an odd number
3. number is an even number
4. number is an odd number
1. {1, 2, 3, 3, 2, 4, 5, 5}
2. {1, 2, 3, 4, 5} [ANSWER]
3. None
4. {1, 5}
1. {'Hello':'World', 'First': 1}
2. {'World': 'Hello', 1: 'First'} [ANSWER]
3. Can be both A or B
GROWAI
4. None of the above
1. strptime()
2. strftime()
3. Both A and B
4. None of the above
PYTHON INTERVIW QUESTION
74. What will be the output of the following code snippet?
GROWAI
75. What will be the output of the following code snippet?
1. 20 [ANSWER]
2. 45
3. 54
4. 4,5
PYTHON INTERVIW QUESTION
76. What will be the output of the following code snippet?
1. Sunday
2. Wednesday
GROWAI
3. Sunday Monday Tuesday Wednesday [ANSWER]
4. None of the above.
78. As what datatype are the *args stored, when passed into
a function?
1. List.
2. Tuple.
3. Dictionary.
4. None of the above.
PYTHON INTERVIW QUESTION
79. What will be the output of the following code snippet?
1. Lists.
2. Tuples.
GROWAI
3. Dictionary. [ANSWER]
4. None of the above.
1. try
2. except
3. finally [ANSWER]
4. None of These
PYTHON INTERVIW QUESTION
82. What will be the output of the following code snippet?
1. 2 3 -3 3.3 [ANSWER]
2. 3 4 -3 3
3. 2 3 -3 3
4. 2 3 -3 -3.3
1. 3
GROWAI
2. 6
3. 0
4. Error [ANSWER]
84. What keyword is used in Python to raise exceptions?
1. raise [ANSWER]
2. try
3. goto
4. except
1. {1, 2, 3, 4, 5}
2. {1, 3, 5, 6} [ANSWER]
3. {2, 4}
4. None of the above
87. What will be the output of the following code snippet?
1. [1, 2] [ANSWER]
2. [5, 6]
3. [1, 2, 5, 6]
GROWAI
4. [3, 4]
1. datetime [ANSWER]
2. date
3. time
4. timedate
GROWAI
92. What will be the output of the following code snippet?
1. 0 1 2 ….. 15
2. Infinite Loop
GROWAI
3. 0 3 6 9 12 15 [ANSWER]
4. 0 3 6 9 12
1. 10 [ANSWER]
2. 20
3. 50
4. 1
GROWAI
1. Local [ANSWER]
2. Global
3. None
4. Cannot be predicted
PYTHON INTERVIW QUESTION
100. What will be the output of the following code snippet?
GROWAI