Best Python interview questions and answers of the Year

Python Interview Questions

Python was created by Guido van Rossum and initially published on February 20, 1991. It is a programming language written in Python. It is one of the most widely-used and well-liked programming languages available today. Because it is interpreted in nature, it allows for the incorporation of dynamic semantics with ease. It is also a free and open-source programming language with basic and tidy syntax. Python becomes more accessible to developers as a result of this. Python also enables object-oriented programming, and it is the programming language most often used for general-purpose programming.


Python’s popularity is soaring due to its straightforward nature and the ability to create various capabilities with fewer lines of code than other programming languages. Aside from machine learning and artificial intelligence, Python is also utilized in Web development and web scraping, and a variety of other disciplines because of its ability to handle sophisticated calculations via strong libraries. There is a significant need for Python developers in India and around the globe. Companies are eager to provide incredible bonuses and rewards to developers who work on their projects.


As a result of this post, you will be equipped with the most often requested python interview questions and answers that will enable you to shine and get excellent job offers.


We have classified them into the following sections:


  • Python Interview Questions for Freshers
  • Python Interview Questions for Experienced
  • Python OOPS Interview Questions
  • Python Pandas Interview Questions
  • Numpy Interview Questions
  • Python Libraries Interview Questions
  • Python Programming Examples



Python Interview Questions for Freshers


  1. What exactly is Python?

Python is a high-level, interpreted programming language that you may use for various tasks. Because it is a general-purpose programming language, you may use it to create practically any form of the application when combined with the appropriate tools and libraries. Aside from that, Python has features like object-oriented programming, modules, threads, exception handling, and automated memory management, all of which are useful for real-world modeling issues and developing programs to address them.


  1. What are the advantages of programming in Python?

Python is a general-purpose programming language that you can learn in a few hours with a straightforward syntax that prioritizes readability and decreases the cost of program maintenance. Furthermore, the language is scriptable, open-source, and enables third-party packages, encouraging modularity and code reuse by reducing duplication of effort.

Its high-level data structures, paired with dynamic typing and dynamic binding, have attracted many developers who use it for Rapid Application Development and distribution.


  1. What is a dynamically typed language, and how does it differ from a statically typed language?

Before we can comprehend a dynamically typed language, we must first grasp what typing is. Typing is a computer language term that relates to type-checking. The combination of “1” and 2 will result in a type error in a strongly-typed language such as Python since these languages do not provide “type-coercion” (implicit conversion of data types). On the other hand, a weakly typed language, such as Javascript, will simply display the number “12” as a result.


The process of type-checking may be done in two steps. – Static – Before the program is executed, the data types are verified.

Dynamic – During the execution, the data types are verified.

Python is an interpreted language, which means that each statement is executed line by line, and as a result, type checking is done on the fly while the program is being executed. As a result, Python is classified as a Dynamically Typed Language.


  1. What is the definition of an Interpreted language?

An Interpreted language executes its statements line by line instead of a written language. Interpreted languages include programming languages such as Python, Javascript, R, PHP, and Ruby, to name a few examples. In contrast to compiled programs, interpreted programs run straight from the source code without an intermediate compilation process.


  1. What exactly is PEP 8, and why is it so significant?

PEP is an acronym that stands for Python Enhancement Proposal. A Python Engineering Project (PEP) is an official design document that provides information to the Python community or describes a new feature for Python or the processes that run on it. PEP 8 is essential since it describes the style rules for Python code, which is quite crucial. Following these style requirements with sincerity and strictness, it seems, is required of everyone who wishes to contribute to the Python open-source community.


  1. What is the meaning of Scope in Python?

Every object in Python has a scope to perform its functions. In Python, a scope is a section of code that contains an object that is still relevant. Namespaces are used to uniquely identify all items included inside a program. On the other hand, these namespaces have a scope set for them, which allows you to utilize their objects without the need for a prefix. The following are a few instances of scope that you may form to identify all items included inside a program uniquely during code execution in Python:


The term “local scope” refers to the items that are now accessible in the current function.

The term “global scope” refers to the items that have been accessible throughout the code execution since it began.

The scope of a module refers to the global objects of the current module that are available throughout the program.

An outermost scope contains all of the built-in names that the program may call. The items inside this scope are searched last to locate the name that has been referenced.

It is important to note that utilizing keywords such as global, local scope items may be synchronized with global scope objects.


  1. What are lists and tuples, and how do they differ? What is the most significant distinction between the two?

Python may store a collection of items in a list or a tuple, both sequence data structures used by Python. Data types of the items recorded in both sequences might differ from one another. The list [‘Sara, 6, 0.19] is expressed with square brackets, but the tuple (‘ansh,’ 5, 0.97) is represented with parentheses.


How does the genuine difference between the two come into play? The most significant distinction between the two is that, although lists are changeable objects, tuples, on the other hand, are immutable. This implies that lists may be changed, added to, or sliced on the fly, but tuples stay constant and cannot be changed in any way. You may verify the difference by running the following example on Python IDLE:


my_tuple = (‘sara’, 6, 5, 0.97)

my_list = [‘sara’, 6, 5, 0.97]

print(my_tuple[0])     # output => ‘sara’

print(my_list[0])     # output => ‘sara’

my_tuple[0] = ‘ansh’    # modifying tuple => throws an error

my_list[0] = ‘ansh’    # modifying list => list modified

print(my_tuple[0])     # output => ‘sara’

print(my_list[0])     # output => ‘ansh’


  1. What are the common built-in data types in Python?

There are several built-in data types in Python. Although Python doesn’t require data types to be defined explicitly during variable declarations type, errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and is instance() functions to check the type of these variables. These data types can be grouped into the following categories-


None Type: The None keyword in Python represents null values. You may use these NoneType objects to execute the equality operation on a boolean value.


Numeric Kinds: There are three main numeric types: integers, floating-point numbers, and complex numbers. Integers are the simplest of the numeric types. Aside from that, booleans are a sub-type of the integer type.


Following the Python documentation, there are three fundamental Sequence Types: lists, tuples, and range objects, all denoted by the prefix “lists.” The in and not in operators have been defined for them to traverse the elements of a sequence type. These operators are on par with the comparable operations in terms of priority.


Types of Mapping Objects: A mapping object in Python may map hashable variables to random objects. There is currently just one standard mapping type, the dictionary, and all mapping objects are changeable.


Set Types: Currently, Python provides two built-in set types – set and frozenset – which are both useful. The set type is changeable, and it has methods such as add() and deletes () (). The frozenset type is immutable, meaning that you cannot update it once it has been created.


Modules: A module is a built-in type supported by the Python interpreter and the standard types. A single specific action, namely attribute access: mymod.myobj, where mymod is a module and myobj refers to a name declared in m’s symbol table, is supported by the module. The symbol table for the module is stored in a highly specific attribute of the module __dict__; nevertheless, direct assignment to this module is neither feasible nor advised for performance reasons.


Types that can be called: Callable kinds are the types you may apply a function call. There are many user-defined functions, instance methods, generator functions, and other built-in functions, methods, and classes to choose from.

The callable types are described further in the documentation available at (see link above).


  1. What is the meaning of pass in Python?

A null operation is represented by the pass keyword in the Python scripting language. It is often used to fill in blank blocks of code that may be executed at runtime but has not yet been written in the traditional sense. We may encounter certain issues during the execution of the following code if the pass statement is not included in the code.


myEmptyFunc() is defined as follows: # do nothing pass myEmptyFunc() # nothing occurs

The following lines are written without using the pass keyword: # File, “stdin,” line 3 # IndentationError: expecting an indented block.


  1. What are the differences between Python modules and packages?

Modular programming is made possible in Python via Python packages and modules, which are two technologies that allow for this. There are various benefits to modularizing. –

Efficiency: Working on a single module allows you to concentrate on a relatively small fraction of the overall issue at hand. This makes development simpler and less prone to errors in the future.

Object-oriented maintainability: Modules are intended to provide logical boundaries between distinct issue areas. If modules are constructed to minimize interdependency, it is less probable that changes made to one module will influence other modules in the program as a whole.

Modularity allows the reuse of functions specified in a module by other program portions.

Scope: Modules are often defined in a different namespace, which aids in preventing confusion between identifiers from other sections of the application.

Python files with suffix are considered modules in general, and they may include a collection of functions, classes, or variables that have been specified and implemented. You may use the import statement to import and initialize several objects simultaneously. If just a portion of the functionality is required, import the necessary classes or functions using the foo import bar command.

Packages enable dot notation to organize the module namespace hierarchically. In the same way, as modules help prevent conflicts between global variable names, packages help to avoid conflicts between module names similarly.

Creating a package is straightforward since it uses the system’s built-in file structure. So just place the modules in a folder, and you’re done, with the folder name serving as the package name. To import a module or its contents from this package, the package name must be used as a prefix to the module name, separated by a dot.

Note: You may potentially import the package as well. However, it will not import the modules included inside the package to the local namespace, making it virtually ineffective.


  1. In Python, what are the differences between global, protected, and private attributes?

Global variables are defined in the global scope and are accessible to everyone. The global keyword refers to a variable in the global scope used inside a function.

_sara is an example of a protected attribute, which is defined with an underscore prefixed to its identifier, for example. They may still be accessed and edited from outside the class they are declared, but a prudent developer should avoid doing so unless necessary.

Attributes had a double underscore before their identifier, such as __ansh, are private attributes. They cannot be accessed or changed directly from the outside world, and any effort to do so would result in an AttributeError being sent in their direction.


  1. What does the term “self” mean in Python?

In Python, the term self is used to declare an instance of an object belonging to a class. Simultaneously hon is explicitly used as the first argument, but it is only used as an optional parameter in Java. It helps differentiate between the methods and attributes of a class and the variables included inside the class.


What exactly is __init__?

A contructor function in Python is automatically invoked to allocate memory when a new object or instance of a class is created called __init__. Every class has an associated __init__ method called when the class is first created. It is useful in differentiating between methods and attributes of a class and variables defined locally.


# class definition

class Student:

   def __init__(self, fname, lname, age, section):

       self.firstname = fname

       self.lastname = lname

       self.age = age

       self.section = section

# creating a new object

stu1 = Student(“Sara”, “Ansh”, 22, “A2”)


  1. In Python, what is the difference between a break, a continue, and a pass?

Break: The break statement stops the loop instantly, and control is passed to the statement that follows the body of the loop following the break statement.

Continue: With a continue statement, the current iteration of the statement is terminated, and control is transferred to the next iteration of the loop. The continue statement also skips the remaining code in the current iteration.




Similar to an empty statement represented by a semicolon in languages such as Java, C++, Javascript, and others, the pass keyword in Python is often used to fill up empty blocks. As previously described, the pass keyword fills up empty blocks in Python.


pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]

in place of p in pat:

if (p == 0) then pass:

current = p break elif (p percent 2 == 0): current = p break elif

Continuation of the print (p) output => 1 3 1 3 1 print # output (current) # output equals to zero


  1. What are unit tests in Python, and how do they work?

Python’s unit test framework is a tool for doing unit tests.

Unit testing is testing individual components of software independently of one another. Can you think of any reasons why unit testing is necessary? Consider the following scenario: you are developing software with three components, designated as A, B, and C. Consider the following scenario: your program fails at a certain time. What method will you use to determine which component was responsible for the software’s failure? Perhaps it was component A that failed, which in turn caused component B to fail, and as a result, the program as a whole failed. There are a plethora of possible combinations.


As a result, it is critical to thoroughly test every component so that we can determine which component is most likely to be the root cause of the software’s failure and should be eliminated.


  1. What is the definition of docstring in Python?

A documentation string, often known as a docstring, is a multiline string used to document a particular code section in an application.

The function or method’s documentation string should define what it performs.


  1. What is the meaning of slicing in Python?

As the name implies, Slicing is the act of removing portions of anything.

The slicing syntax is [start: stop: step] (start, stop, step).

the beginning index from which to slice a list or tuple is denoted by the symbol start.

Sop is the index representing the end of the game or where to go.

The symbol step represents the number of steps to leap.

The default value for a start is zero, the default value for the stop is the number of items, and the default value for a step is one.

Slicing may be applied to strings, arrays, lists, and tuples, among other data types.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] are the numbers.

make a printout (numbers[1 : : 2]) The following are the results: [2, 4, 6, 8, 10]


  1. Describe how you would make a Python script executable on a Unix system.

It is required that the script file begins with #!/usr/bin/env python.


  1. What is the difference between Python Arrays and Python Lists?

When using Python, arrays may only include components of the same data type, which means that the data type of the array should be homogenous. It is a lightweight wrapper over C language arrays, and it uses much less memory than list-based implementations.


Unlike other programming languages, Python allows lists to include components of multiple data types, i.e., the data type of lists may be heterogeneous. It has the drawback of using a significant amount of memory.

arrays to be imported


a = array.array(‘i’, [1, 2, 3])

for i in a:

    print(i, end=’ ‘)    #OUTPUT: 1 2 3

a = array.array(‘i’, [1, 2, ‘string’])    #OUTPUT: TypeError: an integer is required (got type str)

a = [1, 2, ‘string’]

for i in a:

   print(i, end=’ ‘)    #OUTPUT: 1 2 string


Python Interview Questions for Experienced:


  1. How is memory handled in the Python programming language?

The Python Memory Manager manages memory management in the Python programming language. The manager has allocated a private heap area devoted to Python as part of the memory allocation process. All Python objects are kept in this private heap, which is unavailable to the programmer since it is private. On the other hand, Python provides several fundamental API methods for working with the private heap region.

Additionally, Python has a built-in garbage collection system that recycles unused memory to allocate private heap space.


  1. What are Python namespaces, and how do they work? What is the purpose of using them?

In Python, a namespace guarantees that object names in a program are unique and that you may use them without causing any conflicts. Python implements these namespaces as dictionaries, with the key being the name and the value being the object associated with the key. This enables various namespaces to use the same name and map it to a different object simultaneously. As an illustration, consider the following namespacing examples:


Local Namespace refers to the names that are used inside a function. A temporary namespace is formed after a function call is made, which is then deleted when the function is completed.


The names of different imported packages/modules currently being utilized in the current project are stored in the Global Namespace. This namespace is generated when the package is imported into the script, and it remains in effect until the script is executed successfully.


The Built-in Namespace contains built-in functions from the Python core and built-in names for different sorts of exceptions.


The lifespan of a namespace is determined by the scope of the objects to which it is assigned. When the scope of an object expires, the lifespan of the namespace associated with that object also expires. As a result, it is not feasible to access objects in an inner namespace from an outside namespace.


  1. What is Scope Resolution in Python, and how does it work?

Objects within the same scope may have the same name yet sometimes perform distinct functions. In certain instances, Python’s scope resolution mechanism kicks in immediately. Here are a few instances of this kind of behavior:


Math and Cmath modules, respectively, include a large number of functions that are shared by both – log10(), acos(), exp(), and other functions of this kind. To address this issue, it is required to prefix them with the name of the corresponding module, such as math. exp() and cmath.exp(), respectively ().


Consider the following code: a temporary object temp has been initialized to 10 globally and subsequently to 20 on the call to the method. The call to the function, on the other hand, did not modify the value of the temp variable worldwide. It is evident from this example that Python distinguishes clearly between global and local variables, considering their namespaces as distinct identities.


temp = 10   # global-scope variable

def func():

     temp = 20   # local-scope variable


print(temp)   # output => 10

func()    # output => 20

print(temp)   # output => 10

This behavior can be overridden using the global keyword inside the function, as shown in the following example:


temp = 10   # global-scope variable

def func():

     global temp

     temp = 20   # local-scope variable


print(temp)   # output => 10

func()    # output => 20

print(temp)   # output => 20


  1. What are decorators in the context of Python?

Decorators in Python are simply functions that it may use to extend the functionality of an existing function in Python without altering the structure of the original function. In Python, they are represented by the @decorator name variable and are invoked in a bottom-up manner, as seen below. As an illustration:


# decorator function to convert to lowercase

def lowercase_decorator(function):

   def wrapper():

       func = function()

       string_lowercase = func.lower()

       return string_lowercase

   return wrapper

# decorator function to split words

def splitter_decorator(function):

   def wrapper():

       func = function()

       string_split = func.split()

       return string_split

   return wrapper

@splitter_decorator # this is executed next

@lowercase_decorator # this is executed first

def hello():

   return ‘Hello World’

hello()   # output => [ ‘hello’ , ‘world’ ]

The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing them to the function itself. The inner nested function, i.e. ‘wrapper’ function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.


# decorator function to capitalize names

def names_decorator(function):

   def wrapper(arg1, arg2):

       arg1 = arg1.capitalize()

       arg2 = arg2.capitalize()

       string_hello = function(arg1, arg2)

       return string_hello

   return wrapper


def say_hello(name1, name2):

   return ‘Hello ‘ + name1 + ‘! Hello ‘ + name2 + ‘!’

say_hello(‘sara’, ‘ansh’)   # output => ‘Hello Sara! Hello Ansh!’


  1. What is the difference between Dict and List comprehensions?

Comprehensions in Python, like decorators, are syntactic sugar structures that assist in constructing changed and filtered lists, dictionaries, and sets from a given list, dictionary, or set of items. The use of comprehensions saves a significant amount of time and code that would otherwise be much more verbose (containing more lines of code). Let’s look at some instances of situations in which comprehensions might be beneficial:


Performing mathematical operations on the entire list

my_list = [2, 3, 5, 7, 11]

squared_list = [x**2 for x in my_list]    # list comprehension

# output => [4 , 9 , 25 , 49 , 121]

squared_dict = {x:x**2 for x in my_list}    # dict comprehension

# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Performing conditional filtering operations on the entire list

my_list = [2, 3, 5, 7, 11]

squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension

# output => [9 , 25 , 49 , 121]

squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension

# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one

Comprehensions allow for multiple iterators and combine multiple lists into one. 


a = [1, 2, 3]

b = [7, 8, 9]

[(x + y) for (x,y) in zip(a,b)]  # parallel iterators

# output => [8, 10, 12]

[(x,y) for x in a for y in b]    # nested iterators

# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)] 

Flattening a multi-dimensional list

A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements. 


my_list = [[10,20,30],[40,50,60],[70,80,90]]

flattened = [x for temp in my_list for x in temp]

# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

Note: List comprehensions have the same effect as the map method in other languages. They follow Python’s mathematical set builder notation rather than map and filter functions.


  1. What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python that can accept any number of arguments but can only have a single expression. It is generally used in situations requiring an anonymous function for a short period. You can use lambda functions in either of the two ways:


Assigning lambda functions to a variable:

mul = lambda a, b : a * b

print(mul(2, 5))    # output => 10

Wrapping lambda functions inside another function:

def myWrapper(n):

 return lambda a : a * n

mulFive = myWrapper(5)

print(mulFive(2))    # output => 10


  1. What is the syntax for copying an object in Python?

The assignment statement (= operator) in Python does not duplicate objects; instead, it creates new objects. Instead, it establishes a connection between the existing object and the name of the target variable. To make multiple copies of an object in Python, we must use the copy module. Furthermore, there are two methods for producing duplicates of an object using the copy module – one is to use the copy module directly, and the other is to use the copy module indirectly.


Copy is a bit-wise copy of an object, to put it another way. The values in the duplicated object generated are an identical replica of the values in the original object that was created. The reference addresses for the objects in question are replicated only if one of the values references another.


Deep Copy replicates all values from the source object to the target object in a recursive manner, i.e., it duplicates the objects referenced by the source object.


from copy import copy, deepcopy

list_1 = [1, 2, [3, 5], 4]

## shallow copy

list_2 = copy(list_1) 

list_2[3] = 7


list_2    # output => [1, 2, [3, 5, 6], 7]

list_1    # output => [1, 2, [3, 5, 6], 4]

## deep copy

list_3 = deepcopy(list_1)

list_3[3] = 8


list_3    # output => [1, 2, [3, 5, 6, 7], 8]

list_1    # output => [1, 2, [3, 5, 6], 4]


  1. What is the difference between the Python functions xrange and range?

In terms of functionality, the methods xrange() and range() are quite similar. Each of these functions generates a sequence of integers, with the only difference being that range() produces a Python list, but xrange() returns an xrange object, as opposed to the other way around with range().


So, how does this make a difference to you in the long term? In contrast to range(), xrange() does not produce a static list; rather, it generates the value as it goes along, in contrast to range() (). In the programming world, this strategy, generally used with an object-type generator, is referred to as “yielding.”


Allowing for the possibility of yielding is crucial in circumstances when memory is a constraint. The use of a static list, such as range(), may result in a Memory Error in such cases; however, the use of xrange() may handle it better by employing just the amount of memory required by the generator (significantly less in comparison).


for i in xrange(10):    # numbers from o to 9

   print i       # output => 0 1 2 3 4 5 6 7 8 9

for i in xrange(1,10):    # numbers from 1 to 9

   print i       # output => 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10, 2):    # skip by two for next

   print i       # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range does the same as what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.


  1. What is the difference between pickling and unpickling?

Serialization is a functionality provided by the Python library out of the box. It is possible to serialize an object by converting it into a format that it can save and then deserialize it to get back what was created. The pickle module comes into action at this point.


Pickling is the name of the serialization process in Python, which is also known as pickling. The serialization of any object in Python creates a byte stream that may be stored as a file in memory. Pickling is a compact process, but it may compact the pickle items themselves much more. Furthermore, pickle retains track of the items that it has serialized, and the serialization is portable across different versions of the program.


Pickle. dump is the function you can utilize in the preceding step ().


Unpickling: Unpickling is the polar opposite of pickling in every way. It deserializes the byte stream to rebuild the objects previously contained in the file and then loads it into memory.


Pickle.load is the function utilized in the preceding procedure ().


Take note that Python also has a second, more rudimentary serialization module called marshall, which exists mainly to support.pyc files in Python and varies drastically from the pickle.


  1. What are Python generators, and how do they work?


In computing, generators are functions that return an iterable collection of elements in a predefined order, one item at a time. Generators, in general, are used to generate iterators that use a different approach from the one that got previously employed to identify all items included inside a program uniquely parent class members. To return a generator object, they utilize the yield keyword rather than the return statement.


Let’s see if we can create a generator for the Fibonacci numbers –


## generate fibonacci numbers upto n

def fib(n):

   p, q = 0, 1

   while(p < n):

       yield p

       p, q = q, p + q

x = fib(10)    # create generator object 


## iterating using __next__(), for Python2, use next()

x.__next__()    # output => 0

x.__next__()    # output => 1

x.__next__()    # output => 1

x.__next__()    # output => 2

x.__next__()    # output => 3

x.__next__()    # output => 5

x.__next__()    # output => 8

x.__next__()    # error


## iterating using loop

for i in fib(10):

   print(i)    # output => 0 1 1 2 3 5 8


  1. What is the meaning of PYTHONPATH in Python?

PYTHONPATH is an environment variable that you may use to specify extra directories in which Python will look for modules and packages when searching for them. This is particularly important when it comes to maintaining Python libraries that you do not want to install on the global default location of your computer.


  1. The help() and dir() methods are useful, but what is their purpose?

The help() method in Python shows documentation for modules, classes, functions, keywords, and other data types in the program. A help() method is invoked if no parameters are supplied to it, in which case an interactive help utility is started on the console.


The dir() function’s goal is to produce a proper list of attributes and methods for the object it is invoked. It operates differently with various objects because it strives to generate the most relevant data, rather than the whole information, rather than the complete information.


If the object is a Module or a Library, it lists all the characteristics included inside that module.

The function produces a list of all valid attributes and basic attributes for Class Objects when called on a Class Object.

It produces a list of characteristics that are currently available in the current scope if no arguments are given.


  1. What is the distinction between Python and Python C code?


Python (.py) files are used to store the source code. The.pyc file, on the other hand, contains the bytecode of your application. Following the compilation of file, we have bytecode (source code). All of the files that you execute do not have.pyc files written for them. It is only made for the files you load into your computer system.


The python interpreter checks for compiled files before running a python program. If the file is there, the virtual machine will use it to carry out its instructions. If file is not found, it searches for it. If discovered, it is compiled into an a.pyc file, then executed by the Python virtual machine.


The presence of an a.pyc file reduces the amount of time spent compiling.


  1. What is the Python interpreter?

Python is neither an interpreted nor a compiled language in the traditional sense. The implementation’s ability to be interpreted or compiled is a property. Python is a bytecode (a collection of interpreter-readable instructions) that may be interpreted differently.


The source code is included in a file with suffix.


Python converts source code into a collection of instructions that it can execute on a virtual computer. The Python interpreter is a virtual computer that implements the virtual machine. “Bytecode” is the name given to this intermediate format. source code is first compiled into.pyc, bytecode, before being executed. This bytecode may subsequently be interpreted by the standard CPython interpreter or by the JIT(Just in Time compiler) that PyPy has built.


  1. In Python, are arguments provided by value or reference, respectively?

Passing by value means passing a copy of the real object. Changing the value of a duplicate of an object will not affect the value of the original object of the same name.


Passing an object via reference means that a reference to the actual object is supplied. It is possible to modify the value of a new object without affecting the value of the old object, though.


In Python, arguments are supplied by reference, which means that a reference to the real object is passed instead of the actual object itself.


def appendNumber(arr):


arr = [1, 2, 3]

print(arr)  #Output: => [1, 2, 3]


print(arr)  #Output: => [1, 2, 3, 4]


  1. What are iterators in the Python programming language?

An iterator is a piece of software.

It keeps track of its current state, i.e., where it is in the process of iteration (see the code below to understand how). The __iter__() function is responsible for initializing an iterator.


It contains a __next__() function, which returns the item that will be iterated through and refers to the next entry in the list. When the iterable object concludes its iteration, the function __next__() must throw the StopIteration exception.


It also has the property of being self-iterable.


Iterators are objects that allow us to iterate across iterable items such as lists, strings, and other similar things.


ArrayList is a kind of collection.

   def __init__(self, number_list):

       self.numbers = number_list

   def __iter__(self):

       self.pos = 0

       return self

   def __next__(self):

       if(self.pos < len(self.numbers)):

           self.pos += 1

           return self.numbers[self.pos – 1]


           raise StopIteration

array_obj = ArrayList([1, 2, 3])

it = iter(array_obj)

print(next(it)) #output: 2

print(next(it)) #output: 3


#Throws Exception

#Traceback (most recent call last):




  1. Explain how to delete a file in Python?

Use command os.remove(file_name)

import os


print(“File Removed!”)


  1. Explain split() and join() functions in Python?

You can use split() function to split a string based on a delimiter to a list of strings.

You can use join() function to join a list of strings based on a delimiter to give a single string.

string = “This is a string.”

string_list = string.split(‘ ‘) #delimiter is ‘space’ character or ‘ ‘

print(string_list) #output: [‘This’, ‘is’, ‘a’, ‘string.’]

print(‘ ‘.join(string_list)) #output: This is a string.


  1. What does *args and **kwargs mean?


*args is a special syntax used in the function definition to pass variable-length arguments.

“*” means variable length, and “args” is the name used by convention. You can use any other.

def multiply(a, b, *argv):

   mul = a * b

   for num in argv:

       mul *= num

   return mul

print(multiply(1, 2, 3, 4, 5)) #output: 120



**kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.

Here, also, “kwargs” is used just by convention. You can use any other name.

Keyworded argument means a variable that has a name when passed to a function.

It is actually a dictionary of the variable names and its value.

def tellArguments(**kwargs):

   for key, value in kwargs.items():

       print(key + “: ” + value)

tellArguments(arg1 = “argument 1”, arg2 = “argument 2”, arg3 = “argument 3”)


# arg1: argument 1

# arg2: argument 2

# arg3: argument 3


  1. What are negative indexes, and why are they used?

Negative indexes are the indexes from the end of the list or tuple or string.

Arr[-1] means the last element of array Arr[]

arr = [1, 2, 3, 4, 5, 6]

#get the last element

print(arr[-1]) #output 6

#get the second last element

print(arr[-2]) #output 5


Python OOPS Interview Questions


  1. How does one go about creating a Python class?

To create a class in Python, the keyword “class” is used, as seen in the following example:


class InterviewbitEmployee:

   def __init__(self, emp_name):

       self.emp_name = emp_name

To instantiate or create an object from the class created above, we do the following:


emp_1=InterviewbitEmployee(“Mr. Employee”)

To access the name attribute, we just call the attribute using the dot operator as shown below:



# Prints Mr. Employee

To create methods inside the class, we include the methods under the scope of the class as shown below:


class InterviewbitEmployee:

   def __init__(self, emp_name):

       self.emp_name = emp_name


   def introduce(self):

       print(“Hello I am ” + self.emp_name)

The self argument in the init and introduce functions represents a reference to the current class instance, which is used to access the attributes and methods of that class. The self parameter in the init and introduce functions represents the current class instance. Any method created inside the class that takes a self argument must take it as the first parameter. You may go to a method of the class InterviewbitEmployee by calling the method illustrated below:



The overall program would look like this:


class InterviewbitEmployee:

   def __init__(self, emp_name):

       self.emp_name = emp_name


   def introduce(self):

       print(“Hello I am ” + self.emp_name)


# create an object of InterviewbitEmployee class

emp_1 = InterviewbitEmployee(“Mr Employee”)

print(emp_1.emp_name)    #print employee name

emp_1.introduce()        #introduce the employee


  1. How does inheritance operate in the Python programming language? Give an illustration of what you mean.

The ability to access all properties and methods of another class is granted to a class via inheritance. It contributes to code reusability and makes it easier for developers to maintain programs without writing duplicate code. Child classes, also known as derived classes, are derived from another class in the inheritance hierarchy. The class from which the child class members are derived is the parent class or superclass.


Python supports many types of inheritance, the most common of which are as follows:

Single Inheritance: Members of a child class are descended from a single parent class.


# Parent class

class ParentClass:

    def par_func(self):

         print(“I am parent class function”)


# Child class

class ChildClass(ParentClass):

    def child_func(self):

         print(“I am child class function”)


# Driver code

obj1 = ChildClass()



There is a multi-level inheritance structure: the parent class members are passed down to a child class, which is then passed down to another child class (B). The characteristics of both the base and derived classes are passed down to the new derived class, C, via inheritance. Class A, in this case, is the grandparent class of class C.


# Parent class

class A:

   def __init__(self, a_name):

       self.a_name = a_name


# Intermediate class

class B(A):

   def __init__(self, b_name, a_name):

       self.b_name = b_name

       # invoke constructor of class A

       A.__init__(self, a_name)


# Child class

class C(B):

   def __init__(self,c_name, b_name, a_name):

       self.c_name = c_name

       # invoke constructor of class B

       B.__init__(self, b_name, a_name)


   def display_names(self):

       print(“A name : “, self.a_name)

       print(“B name : “, self.b_name)

       print(“C name : “, self.c_name)


#  Driver code

obj1 = C(‘child’, ‘intermediate’, ‘parent’)




Many Inheritance: This is accomplished when a single child class simultaneously inherits members from multiple parent classes. All of the characteristics of the parent classes are passed down to the kid class.


# Parent class1

class Parent1:

   def parent1_func(self):

       print(“Hi I am first Parent”)


# Parent class2

class Parent2:

   def parent2_func(self):

       print(“Hi I am second Parent”)


# Child class

class Child(Parent1, Parent2):

   def child_func(self):




# Driver’s code

obj1 = Child()


As the name implies, hierarchical inheritance is defined as the process of more than one child class deriving from a parent class at the same time.


# Base class

class A:

     def a_func(self):

         print(“I am from the parent class.”)


# 1st Derived class

class B(A):

     def b_func(self):

         print(“I am from the first child.”)


# 2nd Derived class

class C(A):

     def c_func(self):

         print(“I am from the second child.”)


# Driver’s code

obj1 = B()

obj2 = C()


obj1.b_func()    #child 1 method


obj2.c_func()    #child 2 method


  1. How do you get access to the members of the parent class in the child class?

The following are the many methods for gaining access to members of a parent class inside a child class:

By referring to the parent class as in-place You may access the characteristics of a parent class by using the name of the parent class, as illustrated in the following example:


class Parent(object):  

   # Constructor

   def __init__(self, name): = name    


class Child(Parent): 

   # Constructor

   def __init__(self, name, age): = name

       self.age = age


   def display(self):

       print(, self.age)


# Driver Code

obj = Child(“Interviewbit”, 6)


Using super(): The parent class members can be accessed using the super keyword in child class.

class Parent(object):

   # Constructor

   def __init__(self, name): = name    


class Child(Parent):

   # Constructor

   def __init__(self, name, age):         


       In Python 3.x, we can also use super().__init__(name)


       super(Child, self).__init__(name)

       self.age = age


   def display(self):

      # Note that cant be used 

      # here since super() is used in the constructor

      print(, self.age)


# Driver Code

obj = Child(“Interviewbit”, 6)



  1. Are access specifiers utilized in the Python programming language?

It is important to note that Python does not use access specifiers such as private, public, and protected. It does not, however, deprive any variables of this opportunity. Prefixing variable names with a single underscore (protected) or double underscore (private) can simulate the behavior of the variables in question. By default, variables that do not have prefixed underscores are considered public.



# to demonstrate access specifiers

class InterviewbitEmployee:


    # protected members

    _emp_name = None

    _age = None


    # private members

    __branch = None


    # constructor

    def __init__(self, emp_name, age, branch): 

         self._emp_name = emp_name

         self._age = age

         self.__branch = branch


    #public member

    def display():

        print(self._emp_name +” “+self._age+” “+self.__branch)


  1. Is it feasible to invoke a parent class without having to create an instance of it?

Yes, it is feasible if other child classes instantiate the base class or if the base class is a static method.


  1. How does one go about creating an empty class in Python?

An empty class is a class that does not have any members declared in its definition. You may make an instance of it (the pass command does nothing in python). We may build objects that are not included in this class’s class.

As an illustration-


class EmptyClassDemo:



print(“Name created= “,


Name created = Interviewbit


  1. Make a distinction between new and override modifiers in the paragraph.

You may tell the compiler that you should use the new implementation instead of the base class function by specifying the new modifier. Using the Override modifier, it is possible to override a base class function inside a child class.


  1. What is the purpose of the finalized command?

It is necessary to utilize the finalized method to free up unmanaged resources and clean up before the trash collection function is called. This facilitates the completion of memory management duties.


  1. What is the init method in the Python programming language?

The init function behaves similarly to the constructors in Java code. The method is called as soon as an object is created and is called once per object. You may initialize the object’s properties and default behavior at its instantiation, which is handy for setting up its default behavior.

As an illustration:


class InterviewbitEmployee:


   # init method / constructor

   def __init__(self, emp_name):

       self.emp_name = emp_name


   # introduce method

   def introduce(self):

       print(‘Hello, I am ‘, self.emp_name)


emp = InterviewbitEmployee(‘Mr Employee’)    # __init__ method is called here and initializes the object name with “Mr Employee.”



  1. What is the best way to determine if a class is a child of another class?

Python has a function called issubclass() that you may use to do this. The method informs us if a class is a child of another class by returning true or false depending on the situation.

As an illustration:


class Parent(object):



class Child(Parent):



# Driver Code

print(issubclass(Child, Parent))    #True

print(issubclass(Parent, Child))    #False

We can check if an object is an instance of a class by making use of isinstance() method:

obj1 = Child()

obj2 = Parent()

print(isinstance(obj2, Child))    #False 

print(isinstance(obj2, Parent))   #True 


Python Pandas Interview Questions:


  1. Can you tell me anything about pandas?

Pandas is a Python-based library that is free and open-source, and it is used in data manipulation applications that need high speed. ‘Panel Data’ is derived from the term “Panel Data,” which refers to multidimensional data. This was created in 2008 by Wes McKinney and was intended for use in data analysis applications.

Using Pandas, you may complete the following five essential processes in data analysis: loading the data, cleaning/manipulating it, preparing the data, modeling it, and analyzing the data.


  1. Create a data frame with pandas.

Essentially, a data frame is a 2D changeable and tabular structure for expressing data that has been labeled with axes (rows and columns) in two dimensions.


The following is the syntax for generating a data frame:


import pandas as pd

Data frame = pd.DataFrame( data, index, columns, dtype)



Data – Represents numerous types of data such as series, map, ndarray, lists, dict, etc.

Index – An optional input that indicates a row label’s index in the database.

Columns – An optional parameter for the labels of the columns.


Dtype identifies the data type of each column in the table. Once again, this is entirely optional.


  1. How will you mix data frames from various pandas libraries?

To integrate the data frames, you might use one of the following procedures:


Append () method: This is used to stack the data frames horizontally. Syntax:


Concat () method: This is used to stack data frames vertically. This is best used when the data frames have the same columns and similar fields. Syntax:

pd.Concat([df1, df2]) 

join() method: This is used for extracting data from various data frames having one or more common columns.



  1. Is it possible to generate a series in pandas from the dictionary object?

A series is a one-dimensional array that may store a variety of distinct data kinds in a single location. It is possible to generate pandas series from a dictionary object, as seen below:


import pandas as pd    

dict_info = {‘key1’ : 2.0, ‘key2’ : 3.1, ‘key3’ : 2.2}  

series_obj = pd.Series(dict_info)    

print (series_obj)    


x     2.0

y     3.1

z     2.2

dtype: float64

If an index is not supplied in the input method, then the keys of the dictionaries are sorted in ascending order to build the index for the dictionaries in question. Assuming you’ve entered an index, it will pull any values associated with the index label from the dictionary.


  1. How will you discover and deal with missing values in a data frame?

The isnull() and isna() you may use methods to determine whether or not a dataframe has any missing values.



We can handle missing values by either replacing the values in the column with 0 as follows:



Or by replacing it with the mean value of the column


df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean()))


  1. Can you explain what you mean by reindexing in pandas?

Reindexing is the process of converting a dataframe to a new index, with or without filling logic, as necessary. If any of the values from the preceding index are missing, then NaN/NA is put in the appropriate spot. The existing object gets replaced with a new one unless a new index is created that is comparable to the present one. The value of the copy property is set to False. Changing the index of rows and columns in the dataframe is likewise accomplished by this method.


  1. What is the best way to add a new column to a pandas dataframe?

Adding a column to a pandas dataframe is as simple as the following:


import pandas as pd      

data_info = {‘first’ : pd.Series([1, 2, 3], index=[‘a’, ‘b’, ‘c’]),    

       ‘second’ : pd.Series([1, 2, 3, 4], index=[‘a’, ‘b’, ‘c’, ‘d’])}    


df = pd.DataFrame(data_info)    

#To add new column third


print (df)    

#To add new column fourth


print (df)    


  1. What is the best way to remove indices, rows, and columns from a dataframe?

To delete an index, use the command del, which will remove the index by name.

Alternatively, the value None may be supplied to the

For example, assuming you have the following dataframe in your possession:


                Column 1


   John               1

   Jack               2

   Judy               3

   Jim                4

To drop the index name “Names”: = None

# Or run the below:

# del


        Column 1

John          1

Jack          2

Judy          3

Jim           4

It is possible to eliminate a row or column from a dataframe using the drop() function described below.

The axis parameter is supplied to the drop method, and if the value is 0, it indicates that a row should be dropped/deleted, and if the value is 1, it suggests that you should drop a column.


Additionally, by changing the value of in-place to True, we may attempt to erase the rows and columns that are currently in place. There will be no need for reassignment since the task will be completed as planned.

With the help of the drop duplicates() function, it is possible to remove duplicate values from a row or column.


  1. Is it possible to get products from Series A that are not accessible from another Series B? 

As illustrated in the example below, you may accomplish this by combining the (not/negation symbol) with the isin() method.


import pandas as pd

df1 = pd.Series([2, 4, 8, 10, 12])

df2 = pd.Series([8, 12, 10, 15, 16])





0    2

1    4

dtype: int64


  1. How will you get the goods that are not common to both the specified series A and series B?

The intersection of both series may be obtained by first performing the union of both series and then getting the intersection of both series. After that, we use the strategy of obtaining union items not included in the intersection’s list of elements.

This is shown by the following code:


import pandas as pd

import numpy as np

df1 = pd.Series([2, 4, 5, 8, 10])

df2 = pd.Series([8, 10, 13, 15, 17])

p_union = pd.Series(np.union1d(df1, df2))  # union of series

p_intersect = pd.Series(np.intersect1d(df1, df2))  # intersection of series

unique_elements = p_union[~p_union.isin(p_intersect)]




0     2

1     4

2     5

5    13

6    15

7    17

dtype: int64


  1. Is it possible for the panda’s library to detect dates when importing data from various sources?

Yes, they can, but only with a little assistance. It is necessary to provide the parse dates argument throughout reading data from the sources. Consider the following scenario: while reading data from a CSV file, we may find several date-time formats that the panda’s library does not support. When it comes to building our date parser, pandas provides the flexibility we need with the aid of lambda functions, as seen below:


import pandas as pd

from datetime import datetime

dateparser = lambda date_val: datetime.strptime(date_val, ‘%Y-%m-%d %H:%M:%S’)

df = pd.read_csv(“some_file.csv”, parse_dates=[‘datetime_column’], date_parser=dateparser)


Numpy Interview Questions:


  1. Can you explain what you mean by NumPy?

NumPy is one of the most popular, easy-to-use, adaptable, open-source, python-based, general-purpose packages used for processing arrays. NumPy is a general-purpose package that is used for processing arrays. NumPy is an acronym that stands for NUMerical PYthon. In particular, it is well-known for its highly optimized tools, which result in great speed, and its strong N-Dimensional array processing function, which got created specifically to deal with complicated arrays. Because of its widespread use, high performance, and flexibility in performing a wide range of operations such as trigonometric operations and algebraic and statistical computations, it is the most commonly used computer for performing scientific computations and various broadcasting functions. The applications of NumPy are shown in the following image:


  1. What are the advantages of using NumPy arrays over Python lists?


Python’s list data structure is very efficient and can execute a wide range of tasks in a single operation. However, when it comes to calculating vectorized operations, such as element-wise multiplication and addition, they suffer significant constraints due to the nature of the data. Python lists also need information about each element’s type, which causes overhead since type dispatching code is executed every time an operation is done on any member in the list. This is where NumPy arrays come into play since they overcome all of the constraints of python lists. NumPy arrays are particularly useful when dealing with large amounts of data.


As NumPy arrays grow, NumPy becomes around 30 times quicker than the Python List, a significant performance improvement. As a result of their homogeneous nature, Numpy arrays are densely packed in memory, resulting in faster overall performance. This guarantees that the memory clean-up process is as quick as possible.


  1. What processes are involved in creating 1D, 2D, and 3-dimensional arrays?

Creation of a 1D array:


import numpy as np

one_dimensional_list = [1,2,4]

one_dimensional_arr = np.array(one_dimensional_list)

print(“1D array is : “,one_dimensional_arr) 

2D array creation:

import numpy as np


two_dimensional_arr = np.array(two_dimensional_list)

print(“2D array is : “,two_dimensional_arr)

3D array creation:

import numpy as np


three_dimensional_arr = np.array(three_dimensional_list)

print(“3D array is : “,three_dimensional_arr) 

ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the creation of a 6D array:

import numpy as np

ndArray = np.array([1, 2, 3, 4], ndmin=6)


print(‘Dimensions of array:’, ndArray.ndim)


  1. You are given a numpy array and a new column as inputs. How will you delete the second column and replace the column with a new column value?


Given array:


[[35 53 63]

[72 12 22]

[43 84 56]]

New Column values:









import NumPy as np


inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])

new_col = np.array([[20,30,40]])

# delete 2nd column

arr = np.delete(sampleArray , 1, axis = 1)

#insert new_col to array

arr = np.insert(arr , 1, new_col, axis = 1)

print (arr) 


  1. How will you load data from a text file in the most effective manner?

In this case, we may make use of the numpy.loadtxt() function, which will automatically read the file’s header and footer lines and any comments, if any.

If you find that this technique is less efficient than you would like, then the data should be expressed in a more efficient format such as CSV or another similar format. Depending on the version of NumPy that is being used, you might evaluate various solutions.


The following are the file types that are compatible with this program:

Text files: These files are often large and slow to download, but they are portable and human-readable.

Binary data in its raw form: This file has no metadata and is thus not portable. They are, nevertheless, quite swift.

Pickle: These are on the verge of being slow and portable, but they are dependent on the NumPy versions available.

HDF5: Also known as the High-Powered Kitchen Sink format, HDF5 is a data format that supports both PyTables and the h5py data format.


NumPy’s native binary data format (.npy) is highly simple, efficient, and portable, and many other programming languages use it.


  1. Describe NumPy’s reading of CSV data into an array.

Using the comma as the delimiter in the genfromtxt() function makes it possible to get this result.


from numpy import genfromtxt

csv_data = genfromtxt(‘sample_file.csv’, delimiter=’,’)


  1. How will you sort the array based on the Nth column?

For example, consider an array arr.


arr = np.array([[8, 3, 2],

          [3, 6, 5],

          [6, 1, 4]])

Let us try to sort the rows by the 2nd column so that we get:


[[6, 1, 4],

[8, 3, 2],

[3, 6, 5]]

We can do this by using the sort() method in numpy as:


import numpy as np

arr = np.array([[8, 3, 2],

          [3, 6, 5],

          [6, 1, 4]])

#sort the array using np.sort

arr = np.sort(arr.view(‘i8,i8,i8’),



We can also perform sorting and that too inplace sorting by doing:


arr.view(‘i8,i8,i8’).sort(order=[‘f1’], axis=0)


  1. How will you find the nearest value in a given numpy array?

We can use the argmin() method of numpy as shown below:


import numpy as np

def find_nearest_value(arr, value):

   arr = np.asarray(arr)

   idx = (np.abs(arr – value)).argmin()

   return arr[idx]

#Driver code

arr = np.array([ 0.21169,  0.61391, 0.6341, 0.0131, 0.16541,  0.5645,  0.5742])

value = 0.52

print(find_nearest_value(arr, value)) # Prints 0.5645


  1. How will you reverse the numpy array using one line of code?

This can be done as shown in the following:


reversed_array = arr[::-1]

where arr = original given array, reverse_array is the resultant after reversing all elements in the input.


  1. How will you determine the form of any NumPy array supplied to you?

To get the shape of the numpy array, we may utilize the shape property of the numpy array. It returns the array’s form in terms of the number of rows and columns in the array and the size of the array.


import numpy as np

arr_two_dim = np.array([(“x1″,”x2”, “x3″,”x4”),

             (“x5″,”x6”, “x7″,”x8” )])

arr_one_dim = np.array([3,2,4,5,6])

# find and print shape

print(“2-D Array Shape: “, arr_two_dim.shape)

print(“1-D Array Shape: “, arr_one_dim.shape)



2-D Array Shape:  (2, 4)

1-D Array Shape:  (5,)


Python Libraries Interview Questions:


  1. Explain the difference between a package and a module in the Python programming language.

The module consists of a single Python script. A module may import objects from other modules (i.e., from other Python files). On the other hand, a package is a folder or directory in which various sub-packages and modules are stored.

A python module is generated by storing a file with the on your computer’s hard drive. This file will include classes and methods that will be reusable across the code and different module configurations.

It is possible to build a Python package by following the methods outlined below:

Create a directory and give it a meaningful name reflecting its functionality.

In this directory, you should only put modules of the same kind.


In this directory, create a file named init .py. Python will recognize that the directory we generated is a package due to this. The contents of this package may be imported into other modules in other packages, allowing the functionality to be reused across several packages.


  1. How many of the most often used built-in modules in Python are there, and what are they?

Python modules are the files that contain python code, which might be in the form of functions, variables, or classes, among other things. These are denoted by extension. The following are the most often encountered built-in modules:










  1. What are lambda functions, and how do they work?

Lambda functions are inline, anonymous functions represented by a single statement in the source code. They are used to create function objects throughout a program. They are capable of accepting an unlimited amount of parameters. They are often used when functions are needed just for a brief period. You may use them in the following ways:


mul_func = lambda x,y : x*y

print(mul_func(6, 4))

# Output: 24


  1. What is the best way to create random numbers?

When working with Python, we may create random numbers via a package named random.

We must first import a random module and then use the random() function, as illustrated in the following example:

The random() function creates float values randomly distributed between 0 and 1.


 import random


To generate customized random numbers between specified ranges, we can use the randrange() method.

Syntax: randrange(beginning, end, step)

For example:

import random



  1. Is it possible to quickly determine if all of the characters in the provided string are alphanumeric?

Making advantage of the isalnum() function, which returns true if the string contains solely alphanumeric characters.


For Example –


“abdc1321”.isalnum() #Output: True

“xyz@123$”.isalnum() #Output: False

Another way is to use match() method from the re (regex) module as shown:


import re

print(bool(re.match(‘[A-Za-z0-9]+$’,’abdc1321′))) # Output: True

print(bool(re.match(‘[A-Za-z0-9]+$’,’xyz@123$’))) # Output: False


What are the distinctions between pickling and unpickling? 76.

In Python, pickling is converting python objects into binary form. On the other hand, Unpickling is the process of converting binary form data into Python objects. It is necessary to pickle items to save them on drives or in external memory locations. Unpickled objects are used to return data in the form of python objects, which you may then process in the same way as python objects.

Python includes a pickle module that you may use to do this. Pickling dumps python objects onto disks with the help of the pickle.dump() function. Unpickling makes advantage of the pickle.load() function to return the data as python objects, useful for debugging.


  1. Define the term GIL.

Global Interpreter Lock (GIL) is an abbreviation for Global Interpreter Lock. This is a mutex that is used to restrict access to Python objects. It also helps to ensure good thread synchronization by preventing deadlocks from occurring. GIL aids with the accomplishment of multitasking (and not parallel computing). The operation of GIL is shown in the figure below.

There are three threads in the figure above, as you can see. The First Thread is the thread that gets the GIL first and begins the I/O execution. When the I/O operations are completed, thread 1 releases the GIL that it has gained, then the second thread picks up to complete the process. The operation is repeated, and the GIL is utilized by various threads alternatingly until all of the threads have finished their respective executions. Awaiting state is entered by threads that do not have the GIL lock, and the threads continue execution only once they have obtained the lock.


  1. Define the PYTHONPATH variable.

It is an environment variable used to include extra directories into a module or a package during the importation of the module or package. PYTHONPATH is used to determine whether or not the newly imported packages or modules are present in the current directories of the Python environment. Not only that, but the interpreter uses this environment variable to determine which module has to be loaded at any given time.


  1. Specify what PIP is.

Python Installer Package (PIP) is an abbreviation for Python Installer Package. As the name implies, installing various Python modules is the purpose of this command. It is a command-line utility that provides a smooth interface for installing several Python modules on a single computer. With no user input required, it searches the internet for the package and downloads and installs it into the working directory without further configuration. The following is the syntax for this: pip install package name>


  1. What Python tools are available for discovering problems and doing static analysis? Is there a Python tool for performing the static analysis?


Yes, tools like as PyChecker and Pylint are available for static analysis and linting tools, respectively. PyChecker is a tool for finding flaws in Python source code files. It also generates alerts for coding errors and the complexity of the code. This need is met by Pylint, which checks for the module’s code standards and supports a variety of plugins to allow unique features to fulfill it.


  1. Note the differences between deep and shallow copies.

It is the duty to construct new objects that contain references to the original components performed by shallow copy. This does not go through recursion to produce copies of the nested items in the hierarchy. It just duplicates the reference information of nested objects.

In Deep Copy, each object is copied independently and completely from the original, and it even replicates all of the nested objects of the original element recursively.


  1. What is the most important function in Python? What is the procedure for invoking it?

In programming languages, the main function is regarded as the point at which a program’s execution begins. However, with Python, it is well known that the interpreter reads the file line by line and interprets it serially. This indicates that the main() method is not provided directly in Python. However, this does not rule out the possibility of simulating the main execution. You may accomplish this by constructing a user-defined main() function and utilizing the __name__ attribute of the python file to identify the function. When you use the variable, you refer to a specific built-in variable that refers to the name of the currently active module. You may accomplish this in the manner illustrated below:


def main():

   print(“Hi Interviewbit!”)

if __name__==”__main__”:



Python Programming Examples:


  1. Write python function, which takes a variable number of arguments.

A function that takes variable arguments is called a function prototype. Syntax:


def function_name(*arg_list)

For example:


def func(*var):

   for i in var:




The * in the function argument represents variable arguments in the function.


  1. What does WAP task require?

The WAP (Write a Program) task requires you to take a series of integers and determine whether or not each number is unique.

To do this, first, convert the list to a set with the help of the set() function and then compare the length of this new set with that of the original list. If they are discovered to be equal, return True.

def check_distinct(data_list):

 if len(data_list) == len(set(data_list)):

   return True


   return False;

print(check_distinct([1,6,5,8]))     #Prints True

print(check_distinct([2,2,5,5,7,8])) #Prints False


  1. Write a program for counting the number of every character of a given text file.

The idea is to use collections and pprint modules as shown below:


import collections

import pprint

with open(“sample_file.txt”, ‘r’) as data:

 count_data = collections.Counter(

 count_value = pprint.pformat(count_data)



Input an array A and write a program to verify and return the pairs of elements in the array whose total value equals a target number N.

This is made simple by the hashing phenomenon, which generates random numbers. For the current value of the array, x, we may utilize a hash map to look it up in our database. If the map has a value of (N-x), then we have found our pair of numbers.


def print_pairs(arr, N):

   # hash set

   hash_set = set()


   for i in range(0, len(arr)):

       val = N-arr[i]

       if (val in hash_set):    #check if N-x is there in set, print the pair

           print(“Pairs ” + str(arr[i]) + “, ” + str(val))



# driver code

arr = [1, 2, 40, 3, 9, 4]

N = 3

print_pairs(arr, N)


  1. Create a program that adds two numbers greater than zero without using the plus operator.

You may accomplish this via the use of bitwise operators.

def add_nums(num1, num2):

   while num2 != 0:

       data = num1 & num2

       num1 = num1 ^ num2

       num2 = data << 1

   return num1

print(add_nums(2, 10))


  1. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants.

ax + by = c

MX + NY = o

By solving the equation, we get:


a, b, c, m, n, o = 5, 9, 4, 7, 9, 4

temp = a*n – b*m

if n != 0:

   x = (c*n – b*o) / temp

   y = (a*o – m*c) / temp

   print(str(x), str(y))


  1. Create a program that matches a string that begins with the letter ‘a’ and ends with four to eight ‘b’s.

In this case, we may conduct a regex pattern comparison using the re module in Python’s re package.

import re

def match_text(txt_data):

       pattern = ‘ab{4,8}’

       if,  txt_data):    #search for pattern in txt_data

           return ‘Match found’


           return(‘Match not found’)

print(match_text(“abc”))         #prints Match not found

print(match_text(“aabbbbbc”))    #prints Match found


  1. Create a program to convert dates from the yyyy-mm-dd format to the dd-mm-yyyy format using the yyyy-mm-dd format as a starting point.

We may use the re module to transform the date string once again, as illustrated in the example below:

import re

def transform_date_format(date):

   return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})’, ‘\\3-\\2-\\1’, date)

date_input = “2021-08-01”


You can also use the datetime module as shown below:


from datetime import datetime

new_date = datetime.strptime(“2021-08-01”, “%Y-%m-%d”).strftime(“%d:%m:%Y”)



  1. Create a program that combines two separate dictionaries. 

When combining, if you come across the same keys again, you may combine the values of the two keys. Create a new dictionary and output it.

We may use the Counter method from the collections module to do this.


from collections import Counter

d1 = {‘key1’: 50, ‘key2’: 100, ‘key3’:200}

d2 = {‘key1’: 200, ‘key2’: 100, ‘key4’:300}

new_dict = Counter(d1) + Counter(d2)



  1. How will you access the dataset of a publicly shared spreadsheet in CSV format saved in Google Drive in what way?

We can use the StringIO module from the io module to read from the Google Drive connection, and then we can use the panda’s library to work with the data we have gotten from the Google Drive link.


from io import StringIO

import pandas

csv_link = “…”

data_source = StringIO.StringIO(requests.get(csv_link).content))

dataframe = pd.read_csv(data_source)




Thisemployeddoparent class members previously essay looked at some of the most often requested interview questions for python programmers. In conjunction with frequent problem practice sessions, you will be better prepared to face any Python-based interview questions. Python has earned a great deal of popularity within the developer community over the years, owing to its simplicity and its capacity to handle very complex calculations. As a result, there is an ever-increasing need for qualified Python developers. Nonetheless, it is worth mentioning that working as a Python developer is advantageous. There is a strong focus placed on the ability to develop high-quality code in Python, in addition to the theoretical understanding of the language. Consequently, keep studying and practice issues, and you will undoubtedly be able to succeed in an interview.