TOP 20 PYTHON INTERVIEW QUESTIONS

 

Python Certification is the most in-demand skill in the programming world. We will introduce you to the most frequently asked questions in Python interviews in this Python Interview Questions blog.

Python’s popularity is skyrocketing due to its simplicity and ability to achieve multiple functionalities in fewer lines of code. Python is also used in Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and a variety of other domains because of its ability to support powerful computations through the use of powerful libraries.

 

As a result, python developers are in high demand in India and around the world. Companies are eager to provide incredible perks and benefits to these developers. We have top most asked  20 questions that will assist you with varying levels of expertise to reap the most benefits.

 

 

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

 

The acronym Python Enhancement Proposal (PEP) stands for Python Enhancement Proposal. PEP 8 is an official design document that informs the Python community or describes a new Python feature or procedure. PEP 8 is especially significant because it defines the Python code style rules. When contributing to the Python open-source community, you must strictly adhere to these style requirements. It promotes a coding style that is both readable and visually appealing.

 

 

2. What exactly is __init__?

 

In Python classes, __init__ is a reserved function that is equivalent to constructors in OOP terminology. The __init__ method is automatically invoked when a new object is created. This procedure allocates memory to the new object as soon as it is created. This method can also be used to create variables. It aids in distinguishing the methods and properties of a class from local variables.

 

 

3. What is the distinction between Python Arrays and Python Lists?

 

Arrays in Python can only contain elements of the same data type, i.e. the array’s data type must be homogeneous. It is a thin wrapper around C language arrays that uses significantly less memory than lists.

Lists in Python can contain elements of various data types, implying that list data types can be heterogeneous. It has the disadvantage of requiring a lot of memory.

 

 

 

4. What is the difference between pickling and unpickling?

 

Serialization is a standard feature of the Python library. Serialization is the process of converting an object into a format that can be saved and then deserialized to return to the original object. In this case, the pickle module is used.

 

Pickling: The serialisation procedure in Python is known as pickling. Any object in Python can be serialised as a byte stream and saved as a memory file. Pickling is a compact process, but pickle objects can be even more compact. Pickle also remembers which objects it has serialised, and the serialisation is cross-version portable.

Pickle.dump is the function that is used in the preceding operation ().

 

Unpickling is the polar opposite of picking. It deserializes the byte stream and loads the object into memory to recreate the objects stored in the file.

The function used for the above process is pickle.load().

 

 

 

5. How is Python interpreted?

 

  • Python as a language is neither interpreted nor compiled. The implementation can be interpreted or compiled. Python is an interpreter-readable bytecode.

 

  • The source code is a.py file.

 

  • Python compiles source code into a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is known as “bytecode.”

 

  • The.py source code is first compiled to produce.pyc, which is bytecode. This bytecode can then be interpreted by the official  CPython or by PyPy’s JIT (Just in Time compiler.

 

 

 

6. What exactly are iterators in Python?

 

  • An iterator is a type of object.

 

  • It remembers its state, that is, where it is during iteration (see code below for details). The __iter__() method initialises an iterator.

 

  • It has a __next__() method that returns and points to the next item in the iteration.

 

  • When the iterable object reaches the end, __next__() must throw the StopIteration exception.

 

  • It is also self-replicable.

 

  • Iterators are objects that allow us to iterate over iterable objects such as lists, strings, and so on.

				
					class ArrayList:
   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]
       else:
           raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration

				
			

 

 

 

7. In Python, how do you make a class?

In Python, we use the keyword “class” to create a class, as shown in the example below:

				
					class InterviewtopEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name

				
			

To create an object from the above-mentioned class, we do the following:

				
					emp_1=InterviewtopEmployee("Mr. Employee")
				
			

To access the name attribute, we simply use the dot operator, as shown below:

				
					print(emp_1.name)
# Prints Mr. Employee

				
			

To create methods within the class, we include the following methods within the class’s scope:

				
					class InterviewtopEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name
       
   def introduce(self):
       print("Hello I am " + self.emp_name)

				
			

In the init and introduction functions, the self parameter represents a reference to the current class instance, which is used to access the class’s attributes and methods. Any method defined within the class must have the self parameter as the first parameter. The following method of the class InterviewbitEmployee can be accessed:

				
					emp_1.introduce()

				
			

The overall program would look like this:

				
					class InterviewtopEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name
       
   def introduce(self):
       print("Hello I am " + self.emp_name)
       
# create an object of InterviewtopEmployee class
emp_1 = InterviewtopEmployee("Mr Employee")
print(emp_1.emp_name)    #print employee name
emp_1.introduce()        #introduce the employee

				
			

 

 

 

8. What are Python modules and packages?

 

Modules are Python files with a.py extension that contain a collection of declared and implemented functions, classes, or variables. They can be imported and initialised once using the import statement. If only partial functionality is required, import the necessary classes or functions from the foo import bar.

 

With Packages, dot notation allows for hierarchical organisation of the module namespace. Packages help avoid conflicts between module names in the same way that modules help avoid conflicts between global variable names.Because it makes use of the system’s inherent file structure, creating a package is simple.

 

So simply place the modules in a folder and voila, the folder name serves as the package name. When importing 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.

 

 

 

9. How do you access parent members in the child class?

The following are the methods for gaining access to parent class members within a child class:

  • Using the Parent class name: As shown in the example below, you can access the attributes by using the name of the parent class:

				
					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("Interviewtop", 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("Interviewtop", 6)
obj.display()


				
			

 

 

 

 

 

10. In Python, what are local variables and global variables?

 

Global Variables: Global variables are variables that are declared outside of a function or in a global space. Any function in the programme can access these variables.


Local Variables: A local variable is any variable declared within a function. This variable exists in local space but not in global space.

 

 

 

11. Is it possible to use access specifiers in Python?


Python does not use access specifiers such as private, public, protected, and so on. This, however, is not derived from any variables. It has the concept of mimicking variable behaviour by prefixing variable names with a single (protected) or double underscore (private). Variables without prefixed underscores are public by default.
Example:

				
					class InterviewtopEmployee:
   
    # 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)

				
			

 

 

12. In Python, how does an empty class get created?


An empty class has no members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside of the class.
As an example-

				
					class EmptyClassDemo:
   pass
obj=EmptyClassDemo()
obj.name="Interviewtop"
print("Name created= ",obj.name)

				
			

 

Output:

Name created = Interviewtop

 

 

 

 

13. What is the distinction between the xrange and range functions?


The range() and xrange() methods in Python can be used to iterate a set number of times in for loops. While there is no xrange in Python 3, the range method works in the same way that xrange did in Python 2.


range() — This function returns a list of numbers produced by the range() function.


xrange() returns a generator object that can only be used to loop through numbers. Because only a specific range is displayed on demand, the term “lazy evaluation” was coined.

 

 

 

 

14. Exactly what is the zip function?


In Python, the zip() function returns a zip object that converts a similar index of many containers to a single index. It takes an iterable, converts it to an iterator, and then aggregates the elements based on the iterable provided. It returns a tuple iterator.

 

 

 

 

15. What is the swap case function in Python?


It’s a string function that converts all uppercase letters to lowercase letters and the other way around. It is used to change the case of an already existing string. This function duplicates the string, including all characters from the swap case.

 

 

 

16. What is the Python init method?

 

The init method functions similarly to Java constructors. When an object is instantiated, the method is called. It is useful for initialising any object attributes or default behaviour during instantiation.
As an example:

				
					class InterviewtopEmployee:

   # 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 = InterviewtopEmployee('Mr. Employee')    # __init__ method is called here and initializes the object name with "Mr. Employee"
emp.introduce()

				
			

 

 

 

17. How will you determine whether a class is a child of another class?

 

This is accomplished by utilising Python’s issubclass() method. The method returns true or false depending on whether a class is a child of another class.
As an example:

				
					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


# 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.a_func()
obj1.b_func()    #child 1 method
obj2.a_func()
obj2.c_func()    #child 2 method



				
			

 

 

 

18. What are the help() and dir() functions for?

 

In Python, the help() function is used to display documentation for modules, classes, functions, keywords, and so on. If no parameters are passed to the help() function, the console displays an interactive help utility.
The dir() function attempts to return a valid list of the object’s attributes and methods. It behaves differently with different objects because it strives to produce the most relevant data rather than the complete picture.

 

  • It returns a list of all attributes contained in a Module/Library object.

  • It returns a list of all valid attributes and base attributes for Class Objects.

  • It returns a list of attributes in the current scope if no arguments are passed.

 

 

 

 

19. What are the split() and join() functions in Python?

 

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

 

  • The join() function can be used to join a list of strings based on a delimiter into 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.']


				
			

 

 

 

 

 

20. In Python, are arguments passed by value or by reference?

Pass by value sends a copy of the actual object. Changing the value of the object’s copy has no effect on the value of the original object.

Passing by reference means passing a reference to the actual object. Changing the value of the new object causes the value of the original object to change.

Arguments in Python are passed by reference, which means that a reference to the actual object is passed.

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

				
			

 

 

 

 

 

This is the end of our topic. We hope we helped you in some way. The topics covered in this Core Python Interview Questions blog are among the most sought-after skillsets for a Python professional, according to recruiters. These Python  Interview Questions will undoubtedly assist you in acing your job interview.


Best wishes for your interview!

 

If you still have any queries, please let us know in the comment section.