52 Python Question Answers
52 Python Question Answers
Questions-Answers
Watch Full Video On Youtube:
https://youtu.be/YeupGcOW-3k
LIST Tuple
1. Lists are mutable 1. Tuples are immutable
2. List is a container to contain different types of 2. Tuple is also similar to list but contains immutable
objects and is used to iterate objects. objects.
3. Syntax Of List 3. Syntax Of Tuple
list = ['a', 'b', 'c', 1,2,3] tuples = ('a', 'b', 'c', 1, 2)
4. List iteration is slower 4. Tuple processing is faster than List.
5. Lists consume more memory 5. Tuple consume less memory
6. Operations like insertion and deletion are better
performed. 6. Elements can be accessed better.
Decorator Coding Example
[expression for item in iterable if conditional] {key:value for (key,value) in iterable if conditional}
Example: Example:
Common Way: Common Way:
l = [] d = {}
for i in range(10): for i in range(1,10):
if i%2: sqr = i*i
l.append(i) d[i] = i*i
print(l) print(d)
Output: Output:
[1, 3, 5, 7, 9] {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
4. How Memory Managed In Python?
❏ Memory management in Python involves a private heap containing all Python objects and data structures.
Interpreter takes care of Python heap and that the programmer has no access to it.
❏ The allocation of heap space for Python objects is done by Python memory manager. The core API of Python
provides some tools for the programmer to code reliable and more robust program.
❏ Python also has a build-in garbage collector which recycles all the unused memory. When an object is no longer
referenced by the program, the heap space it occupies can be freed. The garbage collector determines objects
which are no longer referenced by the program frees the occupied memory and make it available to the heap
space.
❏ The gc module defines functions to enable /disable garbage collector:
Source: https://www.careerride.com/python-memory-management.aspx
5. Difference Between Generators And Iterators
GENERATOR ITERATOR
● Generators are iterators which can execute only once. ● An iterator is an object which contains a countable number of
● Generator uses “yield” keyword. values and it is used to iterate over iterable objects like list,
● Generators are mostly used in loops to generate an iterator tuples, sets, etc.
by returning all the values in the loop without affecting the ● Iterators are used mostly to iterate or convert other objects to
iteration of the loop. an iterator using iter() function.
● Every generator is an iterator. ● Iterator uses iter() and next() functions.
● Every iterator is not a generator.
EXAMPLE:
def sqr(n): Example:
for i in range(1, n+1): iter_list = iter(['A', 'B', 'C'])
yield i*i
print(next(iter_list))
a = sqr(3)
print(next(a))
print(next(iter_list))
print(next(a)) print(next(iter_list))
print(next(a))
Output:
Output: A
1 B
4 C
9
6. What is ‘init’ Keyword In Python?
The __init__.py file lets the Python interpreter know The __init__ method is similar to constructors in C++
that a directory contains code for a Python module. It can
and Java. Constructors are used to initialize the object’s
state.
be blank. Without one, you cannot import modules from
another folder into your project. # A Sample class with init method
class Person:
# init method or constructor
The role of the __init__.py file is similar to the def __init__(self, name):
__init__ function in a Python class. The file essentially self.name = name
Module
The module is a simple Python file that contains collections of functions and global variables and with
having a .py extension file. It is an executable file and to organize all the modules we have the concept called
Package in Python.
A module is a single file (or files) that are imported under one import and used. E.g.
import my_module
Package
The package is a simple 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. The package is simply
a namespace. The package also contains sub-packages inside it.
A package is a collection of modules in directories that give a package hierarchy.
from my_package.abc import a
8. Difference Between Range and Xrange?
Memory Consumption Since range() returns a list of elements, it takes In comparison to range(), it takes less memory.
more memory.
Operations Since it returns a list, all kinds of arithmetic Such operations cannot be performed on xrange().
operations can be performed.
9. What are Generators. Explain it with Example.
Example:
● Generators are iterators which can execute only once. def sqr(n):
for i in range(1, n+1):
● Every generator is an iterator. yield i*i
a = sqr(3)
● Generator uses “yield” keyword.
print("The square are : ")
● Generators are mostly used in loops to generate an iterator by print(next(a))
print(next(a))
returning all the values in the loop without affecting the
print(next(a))
iteration of the loop
Output:
The square are :
1
4
9
10. What are in-built Data Types in Python OR
Explain Mutable and Immutable Data Types
A first fundamental distinction that Python makes on data is about whether or not the value of an object changes.
If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
Float Immutable
tuple Immutable
frozenset Immutable
list Mutable
set Mutable
dict Mutable
Common Questions
In inheritance, the child class acquires the properties and can access class A:
all the data members and functions defined in the parent class. A def display(self):
child class can also provide its specific implementation to the print("A Display")
functions of the parent class.
class B(A):
def show(self):
In python, a derived class can inherit base class by just mentioning
print("B Show")
the base in the bracket after the derived class name. d = B()
d.show()
Class A(B): d.display()
Output:
B Show
A Display
13. Difference Between Local and Global Variable in Python
If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
It is created when the function starts execution and lost It is created before the program’s global execution starts and
when the functions terminate. lost when the program terminates.
Data sharing is not possible as data of the local variable can Data sharing is possible as multiple functions can access the
be accessed by only one function. same global variable.
Parameters passing is required for local variables to access Parameters passing is not necessary for a global variable as it
the value in other function is visible throughout the program
When the value of the local variable is modified in one When the value of the global variable is modified in one
function, the changes are not visible in another function. function changes are visible in the rest of the program.
Local variables can be accessed with the help of statements, You can access global variables by any statement in the
inside a function in which they are declared. program.
It is stored on the stack unless specified. It is stored on a fixed location decided by the compiler.
Source: https://www.guru99.com/local-vs-global-variable.html
14. Explain Break, Continue and Pass Statement
● A break statement, when used inside the loop, will terminate the loop and exit. If used inside nested loops, it will
break out from the current loop.
● A continue statement will stop the current execution when used inside a loop, and the control will go back to the
start of the loop.
● A pass statement is a null statement. When the Python interpreter comes across the pass statement, it does
nothing and is ignored.
Output: Output:
0,1,2,3,4,5,6, 0,1,2,3,4,5,6,8,9, Output:
pass inside function
15. What is 'self' Keyword in python?
The ‘self’ parameter is a reference to the current instance of the class, and is used to access variables that
belongs to the class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"My name is {self.name}. I am {self.age} years old.")
c = Person("Nitin",23)
c.info()
Output:
My name is Nitin. I am 23 years old.
16. Difference Between Pickling and Unpickling?
Pickling:
In python, the pickle module accepts any Python object, transforms it into a string representation, and dumps it into a file by
using the dump function. This process is known as pickling. The function used for this process is pickle.dump()
Unpickling:
The process of retrieving the original python object from the stored string representation is called unpickling.
The function used for this process is pickle.load()
Functions Of List ❏
Functions Of Tuple
cmp(tuple1, tuple2) - Compares elements of both tuples.
❏ sort(): Sorts the list in ascending order. ❏ len(): total length of the tuple.
❏ append(): Adds a single element to a list. ❏ max(): Returns item from the tuple with max value.
❏ extend(): Adds multiple elements to a list. ❏ min(): Returns item from the tuple with min value.
❏ tuple(seq): Converts a list into tuple.
❏ index(): Returns the first appearance of the specified value. ❏ sum(): returns the arithmetic sum of all the items in the tuple.
❏ max(list): It returns an item from the list with max value. ❏ any(): If even one item in the tuple has a Boolean value of True, it returns True.
Otherwise, it returns False.
❏ min(list): It returns an item from the list with min value. ❏ all(): returns True only if all items have a Boolean value of True. Otherwise, it returns
❏ len(list): It gives the total length of the list. False.
❏ list(seq): Converts a tuple into a list. ❏
❏
sorted(): a sorted version of the tuple.
index(): It takes one argument and returns the index of the first appearance of an item in
❏ cmp(list1, list2): It compares elements of both lists list1 and a tuple
list2. ❏ count(): It takes one argument and returns the number of times an item appears in the
❏ type(list): It returns the class type of an object. tuple.
Functions Of Dictionary ❏
Functions Of Set
add(): Adds an element to the set
❏ clear(): Removes all the elements from the dictionary ❏ clear(): Removes all the elements from the set
❏ copy(): Returns a copy of the dictionary ❏ copy(): Returns a copy of the set
❏ fromkeys(): Returns a dictionary with the specified keys and value ❏ difference(): Returns a set containing the difference between two or more sets
❏ get(): Returns the value of the specified key ❏ difference_update(): Removes the items in this set that are also included in another, specified set
❏ items(): Returns a list containing a tuple for each key value pair ❏ discard(): Remove the specified item
❏ intersection(): Returns a set, that is the intersection of two or more sets
❏ keys(): Returns a list containing the dictionary's keys ❏ intersection_update(): Removes the items in this set that are not present in other, specified set(s)
❏ pop(): Removes the element with the specified key ❏ isdisjoint(): Returns whether two sets have a intersection or not
❏ popitem(): Removes the last inserted key-value pair ❏ issubset(): Returns whether another set contains this set or not
❏ setdefault(): Returns the value of the specified key. If the key does not ❏ issuperset(): Returns whether this set contains another set or not
exist: insert the key, with the specified value ❏ pop(): Removes an element from the set
❏ remove(): Removes the specified element
❏ update(): Updates the dictionary with the specified key-value pairs ❏ symmetric_difference(): Returns a set with the symmetric differences of two sets
❏ values(): Returns a list of all the values in the dictionary ❏ symmetric_difference_update(): inserts the symmetric differences from this set and another
❏ cmp(): compare two dictionaries ❏ union(): Return a set containing the union of sets
❏ update(): Update the set with another set, or any other iterable
17. Explain Function of List, Set, Tuple And Dictionary?
Functions Of Set
Functions Of Dictionary ❏ add(): Adds an element to the set
❏ clear(): Removes all the elements from the dictionary ❏ clear(): Removes all the elements from the set
❏ copy(): Returns a copy of the dictionary ❏ copy(): Returns a copy of the set
❏ fromkeys(): Returns a dictionary with the specified keys and ❏ difference(): Returns a set containing the difference between two or more
value sets
❏ get(): Returns the value of the specified key ❏ difference_update(): Removes the items in this set that are also included
❏ items(): Returns a list containing a tuple for each key value in another, specified set
pair ❏ discard(): Remove the specified item
❏ keys(): Returns a list containing the dictionary's keys ❏ intersection(): Returns a set, that is the intersection of two or more sets
❏ pop(): Removes the element with the specified key ❏ intersection_update(): Removes the items in this set that are not present
❏ popitem(): Removes the last inserted key-value pair in other, specified set(s)
❏ setdefault(): Returns the value of the specified key. If the ❏ isdisjoint(): Returns whether two sets have a intersection or not
key does not exist: insert the key, with the specified value ❏ issubset(): Returns whether another set contains this set or not
❏ update(): Updates the dictionary with the specified ❏ issuperset(): Returns whether this set contains another set or not
key-value pairs ❏ pop(): Removes an element from the set
❏ values(): Returns a list of all the values in the dictionary ❏ remove(): Removes the specified element
❏ cmp(): compare two dictionaries ❏ symmetric_difference(): Returns a set with the symmetric differences of
two sets
❏ symmetric_difference_update(): inserts the symmetric differences from
this set and another
❏ union(): Return a set containing the union of sets
❏ update(): Update the set with another set, or any other iterable
18. What are Python Iterators?
❖ An iterator is an object which contains a countable number of values and it is used to iterate over iterable objects
like list, tuples, sets, etc.
❖ Iterators are used mostly to iterate or convert other objects to an iterator using iter() function.
❖ Iterator uses iter() and next() functions.
❖ Every iterator is not a generator.
Example:
Output:
A
B
C
19. Explain Type Conversion in Python.
[(int(), float(), ord(), oct(), str() etc.)]
When you are not clear how many arguments you need to pass to a particular function, then we use *args and **kwargs.
The *args keyword represents a varied number of arguments. It is used to add together the values of multiple arguments
The **kwargs keyword represents an arbitrary number of arguments that are passed to a function. **kwargs keywords are
stored in a dictionary. You can access each item by referring to the keyword you associated with an argument when you passed
the argument.
sum(1,2,3,4,5) Output:
{'A': 1, 'B': 2, 'C': 3}
Output:
15
21. What is "Open" and "With" statement in Python?
f = open("nitin.txt")
content = f.read()
print(content)
f.close()
with open("nitin.txt") as f:
content = f.read()
print(content)
22. Different Ways To Read And Write In A File In Python?
❏ Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error.
This is also the default mode in which file is opened.
❏ Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file
does not exists.
❏ Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning
of the file. Creates the file if the file does not exists
❏ Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at
the beginning of the file.
❏ Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data
being written will be inserted at the end, after the existing data.
❏ Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of
the file. The data being written will be inserted at the end, after the existing data.
❏ Text mode (‘t’): meaning \n characters will be translated to the host OS line endings when writing to a file, and back again when reading.
❏ Exclusive creation (‘x’): File is created and opened for writing – but only if it doesn't already exist. Otherwise you get a FileExistsError.
❏ Binary mode (‘b’): appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
23. What is Pythonpath?
PYTHONPATH is an environment variable which you can set to add additional directories where
python will look for modules and packages
The ‘PYTHONPATH’ variable holds a string with the name of various directories that need to be
added to the sys.path directory list by Python.
The primary use of this variable is to allow users to import modules that are not made installable
yet.
24. How Exception Handled In Python?
Division of Integers Whenever two integers are divided, you get a float When two integers are divided, you always provide integer
value value.
Unicode In Python 3, default storing of strings is Unicode. To store Unicode string value, you require to define them with
“u”.
Syntax The syntax is simpler and easily understandable. The syntax of Python 2 was comparatively difficult to
understand.
https://www.guru99.com/python-2-vs-python-3.html
25. Difference Between Python 2.0 & Python 3.0
Rules of ordering In this version, Rules of ordering comparisons have been Rules of ordering comparison are very complex.
Comparisons simplified.
Iteration The new Range() function introduced to perform iterations. In Python 2, the xrange() is used for iterations.
Leak of variables The value of variables never changes. The value of the global variable will change while using
it inside for-loop.
Backward Not difficult to port python 2 to python 3 but it is never Python version 3 is not backwardly compatible with
compatibility reliable. Python 2.
Library Many recent developers are creating libraries which you can Many older libraries created for Python 2 is not
only use with Python 3. forward-compatible.
https://www.guru99.com/python-2-vs-python-3.html
26. What is ‘PIP’ In Python
Python pip is the package manager for Python packages. We can use pip to install packages that do not
come with Python.
pip 'arguments'
❏ Web Applications
❏ Desktop Applications
❏ Database Applications
❏ Networking Application
❏ Machine Learning
❏ Artificial Intelligence
❏ Data Analysis
❏ IOT Applications
❏ Games and many more…!
28. How to use F String and Format or Replacement Operator?
Output:
Hello, My name is Nitin and I'm Python Developer
Output:
Hello, My name is Nitin and I'm Python Developer
29. How to Get List of all keys in a Dictionary?
Abstraction Encapsulation
Abstraction works on the design level. Encapsulation works on the application level.
Abstraction is implemented to hide unnecessary data and withdrawing Encapsulation is the mechanism of hiding the code and the data
relevant data. together from the outside world or misuse.
It highlights what the work of an object instead of how the object It focuses on the inner details of how the object works. Modifications
works is can be done later to the settings.
Abstraction focuses on outside viewing, for example, shifting the car. Encapsulation focuses on internal working or inner viewing, for
example, the production of the car.
Abstraction is supported in Java with the interface and the abstract Encapsulation is supported using, e.g. public, private and secure
class. access modification systems.
In a nutshell, abstraction is hiding implementation with the help of an In a nutshell, encapsulation is hiding the data with the help of getters
interface and an abstract class. and setters.
https://www.educba.com/abstraction-vs-encapsulation/
Tricky Questions
class A
What Is Diamond Problem? {
What Java does not allow is multiple public void display()
{
inheritance where one class can
System.out.println("class A");
inherit properties from more than one }
class. It is known as the diamond }
problem.
//not supported in Java
class C extends A public class D extends B,C
class B extends A
{
{ {
public static void main(String args[])
@Override @Override {
public void display() public void display() D d = new D();
{ { //creates ambiguity which display() method to call
System.out.println("class B"); System.out.println("class C"); d.display();
} } }
} } }
In the above figure, we find that class D is trying to inherit form class B and class C, that is not allowed in Java.
31. Does Python Support Multiple Inheritance. (Diamond Problem)
class B(A):
def abc(self):
print("b")
class C(A):
def abc(self):
print("c")
class D(B,C):
pass
d = D()
d.abc()
32. How to initialize Empty List, Tuple, Dict and Set?
Empty List:
a = []
Empty Tuple:
a = ()
Empty Dict:
a = {}
Empty Set:
a = set()
33. Difference Between .py and .pyc
❏ .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your
program.
❏ Python compiles the .py files and saves it as .pyc files , so it can reference them in subsequent
invocations.
❏ The .pyc contain the compiled bytecode of Python source files. This code is then executed by
Python's virtual machine .
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[:])
Output:
HelloWorld
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[::])
Output:
HelloWorld
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[:5])
Output:
Hello
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[2:5])
Output:
llo
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[2:8:2])
Output:
loo
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[8:1:-1])
Output:
lroWoll
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[-4:-2])
Output:
or
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
s = 'HelloWorld'
Indexing:
H E L L O W O R L D
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(s[::-1])
Output:
dlroWolleh
34. How Slicing Works In String Manipulation. Explain.
Syntax: Str_Object[Start_Position:End_Position:Step]
t1 = (1,2,3)
t2 = (7,9,10)
t1 = t1 + t2
print("After concatenation is : ", t1 )
Output:
After concatenation is : (1, 2, 3, 7, 9, 10)
35. Can You Concatenate Two Tuples. If Yes, How Is It Possible?
Since it is Immutable?
LIST ARRAY
The list can store the value of different types. It can only consist of value of same type.
The list cannot handle the direct arithmetic operations. It can directly handle arithmetic operations.
The lists are the build-in data structure so we don't need to We need to import the array before work with the array
import it.
The lists are less compatible than the array to store the data. An array are much compatible than the list.
It is suitable for storing the longer sequence of the data item. It is suitable for storing shorter sequence of data items.
We can print the entire list using explicit looping. We can print the entire list without using explicit looping.
Source: https://www.javatpoint.com/python-array-vs-list
37. What Is _a, __a, __a__ in Python?
_a
❏ Python doesn't have real private methods, so one underline in the beginning of a variable/function/method name means
it's a private variable/function/method and It is for internal use only
❏ We also call it weak Private
__a
❏ Leading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass.
❏ Interpreter changes variable name with class extension and that feature known as the Mangling.
❏ In Mangling python interpreter modify variable name with __.
❏ So Multiple time It use as the Private member because another class can not access that variable directly.
❏ Main purpose for __ is to use variable/method in class only If you want to use it outside of the class you can make public
api.
__a__
❏ Name with start with __ and ends with same considers special methods in Python.
❏ Python provide this methods to use it as the operator overloading depending on the user.
❏ Python provides this convention to differentiate between the user defined function with the module’s function
38. How To Read Multiple Values From Single Input?
By Using Split()
Delete By Using clear(): Copy A Dictionary Using copy(): Benefit Of Using Copy():
d1 = {'A':1,'B':2,'C':3} d2 = {'A':1,'B':2,'C':3} d2 = {'A':1,'B':2,'C':3}
d1.clear() print(d2) # {'A': 1, 'B': 2, 'C': 3} print(d2) # {'A': 1, 'B': 2, 'C': 3}
print(d1) #{} d3 = d2.copy() d3 = d2.copy()
print(d3) # {'A': 1, 'B': 2, 'C': 3} print(d3) # {'A': 1, 'B': 2, 'C': 3}
del d2['B']
Delete By Using pop(): print(d2) # {'A': 1, 'C': 3}
d1 = {'A':1,'B':2,'C':3} Copy A Dictionary Using ‘=’: print(d3) # {'A': 1, 'B':2, 'C': 3}
print(d1) #{'A': 1, 'B': 2, 'C': 3} d2 = {'A':1,'B':2,'C':3}
d1.pop('A') print(d2) # {'A': 1, 'B': 2, 'C': 3}
print(d1) # {'B': 2, 'C': 3} d3 = d2 DrawBack Of Using ‘=’
print(d3) # {'A': 1, 'B': 2, 'C': 3} d2 = {'A':1,'B':2,'C':3}
print(d2) # {'A': 1, 'B': 2, 'C': 3}
Delete By Using del(): d3 = d2
del d1['B'] print(d3) # {'A': 1, 'B': 2, 'C': 3}
print(d1) # {'C': 3} del d2['B']
print(d2) # {'A': 1, 'C': 3}
print(d3) # {'A': 1, 'C': 3}
40. Difference Between Anonymous and Lambda Function
Lambda function:
❏ It can have any number of arguments but only one expression.
❏ The expression is evaluated and returned.
❏ Lambda functions can be used wherever function objects are required.
Anonymous function:
❏ In Python, Anonymous function is a function that is defined without a name.
❏ While normal functions are defined using the def keyword, Anonymous functions are defined using the
lambda keyword.
❏ Hence, anonymous functions are also called lambda functions.
40. Difference Between Anonymous and Lambda Function
Syntax:
Example:
square = lambda x : x * x
square(5) #25
The above lambda function definition is the same as the following function:
def square(x):
return x * x
Anonymous Function: We can declare a lambda function and call it as an anonymous function, without assigning it to a variable.
print((lambda x: x*x)(5))
Above, lambda x: x*x defines an anonymous function and call it once by passing arguments in the parenthesis (lambda x: x*x)(5).
Advance Questions / Rarely asked
Multithreading:
❏ It is a technique where multiple threads are spawned by a process to do different tasks, at about the same
time, just one after the other.
❏ This gives you the illusion that the threads are running in parallel, but they are actually run in a concurrent
manner.
❏ In Python, the Global Interpreter Lock (GIL) prevents the threads from running simultaneously.
Multiprocessing:
❏ It is a technique where parallelism in its truest form is achieved.
❏ Multiple processes are run across multiple CPU cores, which do not share the resources among them.
❏ Each process can have many threads running in its own memory space.
❏ In Python, each process has its own instance of Python interpreter doing the job of executing the
instructions.
https://www.geeksforgeeks.org/difference-between-multithreading-vs-multiprocessing-in-python/
https://www.geeksforgeeks.org/multiprocessing-python-set-1/
Advance Questions / Rarely asked
❏ The Global Interpreter Lock (GIL) of Python allows only one thread to be executed at a time. It is often a hurdle, as it does not
allow multi-threading in python to save time
❏ The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the
control of the Python interpreter.
❏ This means that only one thread can be in a state of execution at any point in time. The impact of the GIL isn’t visible to
developers who execute single-threaded programs, but it can be a performance bottleneck in CPU-bound and
multi-threaded code.
❏ Since the GIL allows only one thread to execute at a time even in a multi-threaded architecture with more than one CPU core,
the GIL has gained a reputation as an “infamous” feature of Python.
❏ Basically, GIL in Python doesn’t allow multi-threading which can sometimes be considered as a disadvantage.
43. How Class and Object Created in Python?
Create a Class:
To create a class, use the keyword ‘class’:
class MyClass:
x=5
Create Object:
Now we can use the class named MyClass to create objects:
(Create an object named obj, and print the value of x:)
obj= MyClass()
print(obj.x)
44. Explain Namespace and Its Types in Python.
Namespace:
❏ In python we deal with variables, functions, libraries and modules etc.
❏ There is a chance the name of the variable you are going to use is already existing as name of another
variable or as the name of another function or another method.
❏ In such scenario, we need to learn about how all these names are managed by a python program.
This is the concept of namespace.
44. Explain Namespace and Its Types in Python.
❏ Global Namespace: This namespace holds all the names of functions and other variables that are included in
the modules being used in the python program. It includes all the names that are part of the Local namespace.
❏ Built-in Namespace: This is the highest level of namespace which is available with default names available as
part of the python interpreter that is loaded as the programing environment. It include Global Namespace
which in turn include the local namespace.
We can access all the names defined in the built-in namespace as follows.
builtin_names = dir(__builtins__)
for name in builtin_names:
print(name)
45. Explain Recursion by Reversing a List.
def reverseList(lst):
if not lst:
return []
return [lst[-1]] + reverseList(lst[:-1])
print(reverseList([1, 2, 3, 4, 5]))
Output:
[5,4,3,2,1]
46. What are Unittests in Python
Unit Testing is the first level of software testing where the smallest testable parts of a software are tested. This is used to validate
that each unit of the software performs as designed. The unittest test framework is python's xUnit style framework. This is how
you can import it.
import unittest
- Unit testing is a software testing method by which individual units of source code are put under various tests to determine
whether they are fit for use (Source). It determines and ascertains the quality of your code.
- Generally, when the development process is complete, the developer codes criteria, or the results that are known to be
potentially practical and useful, into the test script to verify a particular unit's correctness. During test case execution,
various frameworks log tests that fail any criterion and report them in a summary.
- The developers are expected to write automated test scripts, which ensures that each and every section or a unit meets its
design and behaves as expected.
- Though writing manual tests for your code is definitely a tedious and time-consuming task, Python's built-in unit testing
framework has made life a lot easier.
- The unit test framework in Python is called unittest, which comes packaged with Python.
- Unit testing makes your code future proof since you anticipate the cases where your code could potentially fail or produce a
bug. Though you cannot predict all of the cases, you still address most of them.
47. How to use Map, Filter and Reduce Function in Python?
Shallow Copy:
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements.
With a shallow copy, two collections now share the individual elements.
Shallow copying is creating a new object and then copying the non static fields of the current object to the new object. If the field
is a value type, a bit by bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred
object is not, therefore the original object and its clone refer to the same object.
Deep Copy:
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection
duplicated.
Deep copy is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a
value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed. A
deep copy of an object is a new object with entirely new instance variables, it does not share objects with the old. While
performing Deep Copy the classes to be cloned must be flagged as [Serializable].
49. How An Object Be Copied in Python
In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we
can actually change the behavior of code at run-time.
# monkey.py
class A:
def func(self):
print ("func() is called")
We use above module (monkey) in below code and change behavior of func() at run-time by assigning different value.
import monkey
def monkey_func(self):
print ("monkey_func() is called")
Examples:
Output :monkey_func() is called
51. What is Operator Overloading & Dunder Method.
* *
# This is the example of print simple pyramid pattern *****
n = int(input("Enter the number of rows")) ** **
****
# outer loop to handle number of rows *** ***
*** ****
for i in range(0, n): ****
# inner loop to handle number of columns ** ***
***
# values is changing according to outer loop * **
for j in range(0, i + 1):
** *
# printing stars *
print("* ", end="")
* 1
# ending line after each row
** 22
print()
*** 333
**** 4444
*****
Output: 55555
*
**
***
****
*****
Thanks! Hope It Helps You!
Thanks
PS: Don’t Forget To Connect WIth ME.
Regards,
Nitin Mangotra (NitMan)
Connect with me:
Youtube: https://www.youtube.com/c/nitmantalks
Instagram: https://www.instagram.com/nitinmangotra/
LinkedIn: https://www.linkedin.com/in/nitin-mangotra-9a075a149/
Facebook: https://www.facebook.com/NitManTalks/
Twitter: https://twitter.com/nitinmangotra07/
Telegram: https://t.me/nitmantalks/