Back to home

Python Interview QuestionsPython Interview Questions (2022)

Python Programming Interview Questions

Are you completely new to programming? If not then we presume you will be looking for information about why and how to get started with Python.
Fortunately an experienced programmer in any programming language (whatever it may be) can pick up Python very quickly. It's also easy for beginners
to use and learn, so jump in!

Learn More

Python was developed by Guido van Rossum and was released first on February 20, 1991. It is one of the most widely-used and loved programming languages
and is interpreted in nature thereby providing flexibility of incorporating dynamic semantics. It is also a free and open-source language with very simple and clean syntax.
This makes it easy for developers to learn python. Python also supports object-oriented programming and is most commonly used to perform general-purpose programming.

Nowadays python is the most widely used programming by tech giants like Google, Netflix, Facebook. Looks interesting right, then let’s get started.

So, if you are an aspiring Python Developer, it is very important for you to have a strong knowledge of core concepts before you appear for an interview.
In this article, We’ll share a couple of frequently asked questions to Python developer that will definitely help you in clearing your interview with flying colors.

Go through all the questions to enhance your chances of performing well in the interviews. The questions will revolve around the basic and core fundamentals of Python.

So, let’s dive deep into the surplus of useful interview questions on Python.

Python Interview Questions and Answers

What is Python?

Python was created by Guido van Rossum, and released in 1991. It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures, combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial intelligence domain.

It is easy to learn and require less code to develop the applications.

It is widely used for:
 • Web development (server-side).
 • Software development.
 • Mathematics.
 • System scripting.


Python interview questions for coding?

Python is used in various software domains some application areas are given below.

 • Web and Internet Development
 • Games
 • Scientific and computational applications.
 • Image processing and graphic design applications
 • Enterprise and business applications development
 • Operating systems


Python provides various web frameworks to develop web applications. The popular python web frameworks are Django, Pyramid, Flask. Python's SciPy and NumPy helps in scientific and computational application development.

What are the key features of Python?

 • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

 • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x=”I’m a string” without error

 • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private).

 • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python


What type of interview questions asked from python? Programming or scripting?

Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language. To know more about Scripting, you can refer to the Python Scripting Tutorial.

What is the main difference between an interpreter and a compiler?

The interpreter translates one statement at a time into machine code, whereas the compiler translates the entire code at a time into machine code.

What is a dynamically typed language?

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.

Type-checking can be done at two stages -
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

What is Scope in Python?

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution since their inception.
A module-level scope refers to the global objects of the current module accessible in the program.
An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.
💡 Local scope objects can be synced with global scope objects using keywords such as global.

What are the built-in data types in Python?

There are multiples built-in data types in Python. They are int, float, complex, bool, list, tuple, set, dict, str.
💡 You don’t have to tell all the data types present in Python. Mention some of them you mostly use. The interviewer may ask questions based on your answer.

What are mutable and immutable data types?

Mutable data types can be changed after creating them. Some of the mutable objects in Python are list, set, dict.

Immutable data types can’t be changed after creating them. Some of the immutable objects in Python are str, tuple.

What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['barry', 6, 0.19], while tuples are represented with parantheses ('barry', 5, 0.97). But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:

  my_tuple = ('barry', 6, 5, 0.97)
 my_list = ['barry', 6, 5, 0.97]
 print(my_tuple[0]) // output -> barry
 print(my_list[0]) // output -> barry
 my_tuple[0] = 'allen' // modifying tuple => throws an error
 my_list[0] = 'allen' // modifying list => list modified
 print(my_tuple[0]) // output -> barry
 print(my_list[0]) // output -> allen
}




What are Python namespaces?

A namespace in python refers to the name which is assigned to each object in python. The objects are variables and functions. As each object is created, its name along with space(the address of the outer function in which the object is), gets created. The namespaces are maintained in python like a dictionary where the key is the namespace and value is the address of the object. There 4 types of namespace in python-

Built-in namespace– These namespaces contain all the built in objects in python and are available whenever python is running.
Global namespace– These are namespaces for all the objects created at the level of the main program.
Enclosing namespaces– These namespaces are at the higher level or outer function.
Local namespaces– These namespaces are at the local or inner function.

What are decorators in Python?

Decorators are used to add some design patterns to a function without changing its structure. Decorators generally are defined before the function they are enhancing. To apply a decorator we first define the decorator function. Then we write the function it is applied to and simply add the decorator function above the function it has to be applied to. For this, we use the @ symbol before the decorator.

What are global, protected and private attributes in Python?

Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.

Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.

Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

What is slicing in Python?

Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4].

What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

What is the difference between Python Arrays and lists?

Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.

Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

import array
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

Explain pass in Python

Pass means no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left, and nothing has to be written there.

How can you copy an object in Python?

To copy an object in Python, you can try a copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

Explain some methods of string

split – the method is used to split the string at desired points. It returns the list as a result. By default, it splits the string at spaces. We can provide the delimiter as an argument for the method.

>>> a = "This is Logicmojo"
>>> a.split()
['This', 'is', 'Logicmojo
']
>>> a = "1, 2, 3, 4, 5, 6"
>>> a.split(", ")
['1', '2', '3', '4', '5', '6']

join – the method is used to combine the list of string objects. It combines the string objects with the delimiter we provide.

>>> a = ['This', 'is', 'Logicmojo']
>>> ' '.join(a)
'This is Logicmojo'
>>> ', '.join(a)
'This, is, Logicmojo'

💡 Some other methods of strings are: capitalize, isalnum, isalpha, isdigit, lower, upper, center, etc..,

What’s the negative indexing in lists?

The index is used to access the element from the lists. Normal indexing of the list starts from 0.Similar to normal indexing, negative indexing is also used to access the elements from the lists. But, negative indexing allows us to access the index from the end of the list. The start of the negative indexing is -1. And it keeps on increasing like -2, -3, -4, etc.., till the length of the list.

>>> a = [1, 2, 3, 4, 5]
>>> a[-1]
5
>>> a[-3]
3
>>> a[-5]
1

What is Python's parameter passing mechanism?

There are two parameters passing mechanism in Python:
Pass by references
Pass by value
By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function as well. It indicates the original variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is modified to a = 20. Both the variables denote to the same value.

The pass by value is that whenever we pass the arguments to the function only values pass to the function, no reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different values, and original value persists even after modifying in the function.

Python has a default argument concept which helps to call a method using an arbitrary number of arguments.

What is __init__ ?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

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("Barry", "Allen", 20, "B3")

What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:

os, sys, math, JSON etc


What is a lambda function?

An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.

Example:

a = lambda x,y : x*y
print(a(5, 6))
ans -> 30

What does [::-1] do?

[::-1] is used to reverse the order of an array or a sequence.
[::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or list remains unchanged.

Example:
Let' say, arr = [1,2,3,4,5]
print(arr[::-1])
ans -> [5,4,3,2,1]

What advantages do NumPy arrays offer over (nested) Python lists?

1. Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.

2. They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.

3. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

What are iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple). In simple words: Iterators are objects which can be traversed though or iterated upon.

What is a generator in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduce other overheads as well. If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resume from the same when required.

What is pickling and unpickling in Python?

The Python pickle is defined as a module which accepts any Python object and converts it into a string representation. It dumps the Python object into a file using the dump function; this process is called Pickling.

The process of retrieving the original Python objects from the stored string representation is called as Unpickling.

Is Python platform independent?

In general Python is platform independent, but still needs some care to make sure you don't step on some aspects of Operating System or the file system that works differently on other OS-es. Filenames are case sensitive on some OS-es (e.g. Windows).

Explain the difference between range() and xrange()

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use. The only difference is that range returns a Python list object and xrange returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.

What is PYTHONPATH?

It is an environment variable, which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

Explain the difference between a generator and an iterator in Python.

GeneratorIterator
Implemented using a function.Implemented using a class.
Uses the yield keyword.Does not use the yield keyword.
All the local variables before the yield statements are stored.No local variables are used.


Implementation of Iterator

# Function to generate all the non-negative numbers
# up to the given non-negative number.
class UpTo:
    # giving the parameter a default value of 0
    def __init__(self, max = 0):
        self.max = max
    def __iter__(self):
        self.n = 0
        return self
    def __next__(self):
        # The next method will throw an
        # exception when the termination condition is reached.
        if self.n > self.max:
            raise StopIteration
        else:
            result = self.n
            self.n += 1
            return result
for number in UpTo(5):
    print(number)

Implementation of Generator

# Function to generate all the non-negative numbers
# up to the given non-negative number
def upto(n):
  for i in range(n+1):
    # The yield statement is what makes a function 
    # a generator
    yield i
for number in upto(5):
  print(number)

What is defaultdict in Python?

The Python dictionary, dict, contains words and meanings as well as key-value pairs of any data type. The defaultdict is another subdivision of the built-in dict class.

How is defaultdict different?
The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration, an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError.

Does Python have OOps concepts?

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as procedural as well as structural language.

What is the process of compilation and linking in python?

The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that are required in this as:
1. Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
2. Place this file in the Modules/ directory of the distribution which is getting used.
3. Add a line in the file Setup.local that is present in the Modules/ directory.
4. Run the file using spam file.o
5. After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
6. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

What are unpacking operators in Python? How to use them?

The * and ** operators are unpacking operators in Python.
The * unpacking operator is used to assign multiple values to different values at a time from sequence data types.

>>> items = [1, 2, 3]
>>> a, b, c = items
>>> a
1
>>> b
2
>>> c
3
>>> a, *b = items
>>> a
1
>>> b
[2, 3]

The ** unpacking operator is used with dict data types. The unpacking in dictionaries doesn’t work like unpacking with sequence data types.
The unpacking in dictionaries is mostly used to copy key: value items from one dictionary to another.

>>> a = {1:2, 3:4}
>>> b = {**a}
>>> b
{1: 2, 3: 4}
>>> c = {3:5, 5:6}
>>> b = {**a, **c}
>>> b
{1: 2, 3: 5, 5: 6}

What’s the difference between normal function and lambda function?

The functionality of both normal functions and lambda functions are similar. But, we need to write some extra code in normal functions compared to lambda functions for the same functionality.
Lambda functions come in handy when there is a single expression.

How are classes created in Python?

Class in Python is created using the class keyword.

Example:

class Employee:
    def __init__(self, name):
       self.name = name
E1=Employee("barry")
print(E1.name)

What are the main features of OOP when used in Python?

Object Oriented Programming (OOP) in Python isn't much different than in other languages. It has the same major ideas with a different syntax.

We still use the following big concepts:
1. Classes and objects
2. Inheritance
3. Encapsulation
4. Polymorphism
5. Abstraction
The above mentioned are the main ideas of traditional OOP as well. A class in Python is defined using the keyword class. Similarly, objects are the instances of a class.

Explain Inheritance in Python with an example.

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:
Single Inheritance – where a derived class acquires the members of a single super class.
Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
Hierarchical inheritance – from one base class you can inherit any number of child classes
Multiple inheritance – a derived class is inherited from more than one base class.

Does python support multiple inheritance?

Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.

How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

Does python make use of access specifiers?

Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.

How to create an empty class in Python?

An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it’s a null statement.

class foo:
  pass
obj=foo()
obj.name="barry"
print("Name = ",obj.name)

How do you access parent members in the child class?

Following are the ways using which you can access parent class members within a child class:
By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below:

class Parent(object):  
   # Constructor
   def __init__(self, name):
       self.name = name    
 
class Child(Parent): 
   # Constructor
   def __init__(self, name, age):
       Parent.name = name
       self.age = age
 
   def display(self):
       print(Parent.name, self.age)
 
# Driver Code
obj = Child("Barry", 6)
obj.display()

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

class Parent(object):
   # Constructor
   def __init__(self, name):
       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 Parent.name cant be used 
      # here since super() is used in the constructor
      print(self.name, self.age)
  
# Driver Code
obj = Child("Barry", 6)
obj.display()

Why is finalize used?

Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.

How will you check if a class is a child of another class?

This is done by using a method called issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly.

class Parent(object):
   pass   
 
class Child(Parent):
   pass   
 
# 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

Differentiate between new and override modifiers.

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

What is the difference between .py and .pyc files?

 • .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

 • Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.

 • Having .pyc file saves you the compilation time.

What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.

dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

1. For Modules/Library objects, it returns a list of all attributes, contained in that module.

2. For Class Objects, it returns a list of all valid attributes and base attributes.

3. With no arguments passed, it returns a list of attributes in the current scope.

What does *args and **kwargs mean?

*args
*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
**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")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -

Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.

Reusability: Functions defined in a module can be easily reused by other parts of the application.

Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.

Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

💡 You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.

Define GIL.

Global Interpreter Lock (GIL) in python is a process lock or a mutex used while dealing with the processes. It makes sure that one thread can access a particular resource at a time and it also prevents the use of objects and bytecodes at once. This benefits the single-threaded programs in a performance increase. GIL in python is very simple and easy to implement.
A lock can be used to make sure that only one thread has access to a particular resource at a given time.
One of the features of Python is that it uses a global lock on each interpreter process, which means that every process treats the python interpreter itself as a resource.


For example, suppose you have written a python program which uses two threads to perform both CPU and ‘I/O’ operations. When you execute this program, this is what happens:

1. The python interpreter creates a new process and spawns the threads
2. When thread-1 starts running, it will first acquire the GIL and lock it.
3. If thread-2 wants to execute now, it will have to wait for the GIL to be released even if another processor is free.
4. Now, suppose thread-1 is waiting for an I/O operation. At this time, it will release the GIL, and thread-2 will acquire it.
5. After completing the I/O ops, if thread-1 wants to execute now, it will again have to wait for the GIL to be released by thread-2.

How is memory managed in Python?

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap, and the interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.


What is docstring in Python?

The documentation strings or docstrings are used to document a code block. They are also used as multi-line comments. These docstrings are used in the methods of a class to describe what a certain method does. And we can see the method docstring using the help method.

>>> class Car:
...     def __init__(self, color):
...             self.color = color
...
...     def change_color(self, updated_color):
...             """This method changes the color of the car"""
...             self.color = updated_color
...
>>> car = Car('red')
>>> help(car.change_color)
Help on method change_color in module __main__:

change_color(updated_color) method of __main__.Car instance
    This method changes the color of the car

>>>

What is the difference between is and ==?


The == operator is used to check whether two objects have the same value or not. The is operator is used to check whether two objects are referring to the same memory location or not

>>> a = []
>>> b = []
>>> c = a
>>> a == b
True
>>> a is b
False
>>> a is c
True
>>>

What is Monkey Patching


Monkey Patching is an exciting topic of Python. Monkey-patching is a term that refers to modifying a class or module at a run time. In simple words, a class or module's work can be changed at the runtime. Let's understand this concept by real-life example. When we work on a large project, we may encounter a situation where the third-party library is not working well. So we attempt to revise (or change) it from our project. This process is known as monkey patching in Python. Generally, it is avoided by the developer. However, it is a part of the development process. In monkey patching, we can reopen the class and modify its behavior

We know that Python is a dynamic language; classes are mutable, so we can alter them when we want. Let's understand the following example.

import inspect  
  
  
class MonkeyPatch:  
    def __init__(self, n1):  
        self.n1 = n1  
  
    def add(self, other):  
        return (self.n1 + other)  
  
  
obj1 = MonkeyPatch(10)  
obj1.add(20)  
print(inspect.getmembers(obj1, predicate=inspect.ismethod)) 

What are the Dunder/Magic/Special methods in Python?


Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.

What is the difference between xrange and range in Python?

xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object.

So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object-type generator and has been termed as "yielding". Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).

💡 xrange has been deprecated as of Python 3.x. Now range does exactly 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.

What do you know about pandas?

Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis.

Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.

Define pandas dataframe.

A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns.
The syntax for creating dataframe:

  import pandas as pd
 dataframe = pd.DataFrame( data, index, columns, dtype)




where:
data - Represents various forms like series, map, ndarray, lists, dict etc.
index - Optional argument that represents an index to row labels.
columns - Optional argument for column labels.
Dtype - the data type of each column. Again optional.

What do you understand by reindexing in pandas?

Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.

How to add new column to pandas dataframe?

A new column can be added to a pandas dataframe as follows:

  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
 df['third']=pd.Series([10,20,30],index=['a','b','c'])
 print (df)
 #To add new column fourth
 df['fourth']=df['first']+info['third']
 print (df)




How will you combine different pandas dataframes?

The dataframes can be combines using the below approaches:
append() method: This is used to stack the dataframes horizontally. Syntax:
df1.append(df2)
concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the same columns and similar fields. Syntax:
pd.concat([df1, df2])
join() method: This is used for extracting data from various dataframes having one or more common columns.
df1.join(df2)

Can you create a series from the dictionary object in pandas?

One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown 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)    
Output:
x     2.0
y     3.1
z     2.2
dtype: float64

If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary.

What are the significant features of the pandas Library?

The key features of the panda's library are as follows:
1. Memory Efficient
2. Data Alignment
3. Reshaping
4. Merge and join
5. Time Series

How to iterate over a Pandas DataFrame?

You can iterate over the rows of the DataFrame by using for loop in combination with an iterrows() call on the DataFrame.

How to get the items of series A not present in series B?


We can remove items present in p2 from p1 using isin() method.

import pandas as pd  
p1 = pd.Series([2, 4, 6, 8, 10])  
p2 = pd.Series([8, 10, 12, 14, 16])  
p1[~p1.isin(p2)]  

How can we create a copy of the series in Pandas?

We can create the copy of series by using the following syntax:
pandas.Series.copy
Series.copy(deep=True)
The above statements make a deep copy that includes a copy of the data and the indices. If we set the value of deep to False, it will neither copy the indices nor the data.

💡 If we set deep=True, the data will be copied, and the actual python objects will not be copied recursively, only the reference to the object will be copied.

Explain Categorical Data In Pandas?

Categorical data refers to real-time data that can be repetitive; for instance, data values under categories such as country, gender, codes will always be repetitive. Categorical values in pandas can also take only a limited and fixed number of possible values. Numerical operations cannot be performed on such data. All values of categorical data in pandas are either in categories or np.nan.

What is Groupby Function In Pandas?


In Pandas, groupby () function allows the programmers to rearrange data by using them on real-world sets. The primary task of the function is to split the data into various groups.

How Can A Dataframe Be Converted To An Excel File?

To convert a single object to an excel file, we can simply specify the target file’s name. However, to convert multiple sheets, we need to create an ExcelWriter object along with the target filename and specify the sheet we wish to export.

What do you understand by NumPy?


NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its flexibility to perform various operations like trigonometric operations, algebraic and statistical computations, it is most commonly used in performing scientific computations and various broadcasting functions.

How are NumPy arrays advantageous over python lists?


1. The list data structure of python is very highly efficient and is capable of performing various functions. But, they have severe limitations when it comes to the computation of vectorized operations which deals with element-wise multiplication and addition. The python lists also require the information regarding the type of every element which results in overhead as type dispatching code gets executes every time any operation is performed on any element. This is where the NumPy arrays come into the picture as all the limitations of python lists are handled in NumPy arrays.

2. Additionally, as the size of the NumPy arrays increases, NumPy becomes around 30x times faster than the Python List. This is because the Numpy arrays are densely packed in the memory due to their homogenous nature. This ensures the memory free up is also faster.

What are the uses of NumPy?


The open-source numerical library on Python supports multi-dimensional arrays and contains matrix data structures. Different types of mathematical operations can be performed on arrays using NumPy. This includes trigonometric operations as well as statistical and algebraic computations. Numeric and Numarray are extensions of NumPy.

What are the various features of NumPy?


As a powerful open-source package used for array-processing, NumPy has various useful features. They are:
1. Contains a N-dimensional array object
2. It is interolerable; compatible with many hardware and computing platforms
3. Works extremely well with array libraries; sparse, distributed or GPU
4. Ability to perform complicated (broadcasting) functions
5. Tools that enable integration with C or C++ and Fortran code
6. Supports scientific and financial calculations

What are the steps to create 1D, 2D and 3D arrays?


1D array creation:

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_list=[[1,2,3],[4,5,6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is : ",two_dimensional_arr)

3D array creation:

import numpy as np
three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]]
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(ndArray)
print('Dimensions of array:', ndArray.ndim)

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.

What is the difference between copy and view in NumPy?


Copy
1. Returns a copy of the original array.
2. Do not share the data or memory location with the original array.
3. Any modifications made in the copy will not get reflected in the original.

View
1. Returns a view of the original array.
2. Does use the data and memory location of the original array.
Any modifications made in the copy will get reflected in the original.

Define PIP ?


PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is:

pip install (package_name)

What is main function in python? How do you invoke it?

In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function and by using the __name__ property of python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below:

def main():
   print("Hi Logicmojo!")
if __name__=="__main__":
   main()

Write a program which takes a sequence of numbers and check if all numbers are unique.

You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True.

def check_distinct(data_list):
 if len(data_list) == len(set(data_list)):
   return True
 else:
   return False;
print(check_distinct([1,6,5,8]))     #Prints True
print(check_distinct([2,2,5,5,7,8])) #Prints False

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

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

import collections
import pprint
with open("sample_file.txt", 'r') as data:
 count_data = collections.Counter(data.read().upper())
 count_value = pprint.pformat(count_data)
print(count_value)

Write a Program to add two integers >0 without using the plus operator.

We can use bitwise operators to achieve this.

def add_nums(num1, num2):
   while num2 != 0:
       data = num1 & num2
       num1 = num1 ^ num2
       num2 = data << 1
   return num1
print(add_nums(2, 10))

How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive?

We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source.

from io import StringIO
import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())

Write a python program to check if the number given is a palindrome or not

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0)
    dig=n%10
    rev=rev*10+dig
    n=n//10
if(temp==rev):
    print("The number is a palindrome!")
else:
    print("The number isn't a palindrome!")

How to remove spaces from a string in Python?

Spaces can be removed from a string in python by using strip() or replace() functions. Strip() function is used to remove the leading and trailing white spaces while the replace() function is used to remove all the white spaces in the string:

str = ”logic mojo”
print(str.replace(” “,””))
ans-> logicmojo

What is unittest in Python?

Unittest is a unit testinf framework in Python. It supports sharing of setup and shutdown code for tests, aggregation of tests into collections,test automation, and independence of the tests from the reporting framework.

How is Multithreading achieved in Python?

Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.
Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.

Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.

We can again use the datetime module to convert the date string as shown below:

from datetime import datetime
new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y")
print(new_data)

Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.

We can use the re module of python to perform regex pattern comparison here.

import re
def match_text(txt_data):
       pattern = 'ab{4,8}'
       if re.search(pattern,  txt_data):    #search for pattern in txt_data
           return 'Match found'
       else:
           return('Match not found')
print(match_text("abc"))         #prints Match not found
print(match_text("aabbbbbc"))    #prints Match found

Are there any tools for identifying bugs and performing static analysis in python?

Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module’s coding standards and supports different plugins to enable custom features to meet this requirement.

Write python function which takes a variable number of arguments.

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

Example:

def func(*var):
   for i in var:
       print(i)
func(1)
func(20,1,6)

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

Write a program to check and return the pairs of a given array whose sum value is equal to a target value.

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))
       hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 3
print_pairs(arr, N)

Explain the ternary operator in Python.

Unlike C++, we don’t have ?: in Python, but we have this:
[on true] if [expression] else [on false]
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed.


🚀Conclusion

We have now reached the end of this page. With the knowledge from this page, you should be able to create your own programmes with some research, and it's in fact recommended to hone your programming skills with small projects. There is no way to cover all the information you need to be a successful programmer in one course. In fact, programming is a constant learning process, regardless of whether you are a seasoned professional developer or a newbie.

TEST YOUR KNOWLEDGE!


x
1. Is Python code compiled or interpreted?




2. Python supports the creation of anonymous functions at runtime, using a construct called __________




3. How is a code block indicated in Python?




4. Which of the following concepts is not a part of Python?



5. What will be the output of the following code snippet?
def solve(a, b):
   return b if a == 0 else solve(b % a, a)
print(solve(20, 50))




6. Which of the following types of loops are not supported in Python?



7. What will be the output of the following code snippet?
a = [1, 2]
print(a * 3)




8. Which of the following functions converts date to corresponding time in Python?




9. What will be the output of the following code snippet?
a = "4, 5"
nums = a.split(',')
x, y = nums
int_prod = int(x) * int(y)
print(int_prod)




10. As what datatype are the *args stored, when passed into a function?






logicmojoContact

HAVE A QUESTION? GIVE US A CALL OR CONTACT US - WE'D LOVE TO HEAR FROM YOU

PHONE: +91 80889-75867

WhatsApp : Click Here...

FEEDBACKFORM