Top 50 Python Interview Questions and Answers

You might be a kingpin in writing the Python code, but, attending an interview unprepared is a big no-go. An organized interview preparation should be on the top of your mind before attending one. So, what are the common questions the top employers like Microsoft, Amazon, or Google look for? What goes behind that intelligent brain of the interviewer during an interview? We will look at these questions before proceeding to the list of 50 most commonly asked Python interview questions.

The interviewers typically have a set of questions to test the skills of the interviewee. A no-brainer, right? But, do the evaluators come with a list of questions in mind. Arguably, the experts believe that their trend usually depends on how well you answer the questions. And the interviewers take it from there.

50 Top Python Interview Questions

Python is touted to be an easy-to-learn, multi-paradigm, general-purpose programming language. But, don’t forget Python is fraught with libraries which makes the life of a programmer easy. This means you need to cover a lot of ground when attending the interview. Here’s our compilation of 50 common Python interview questions.

Based on the intensity of the questions we have divided the list into two parts:

  • The Python interview questions for Freshers
  • The Python interview questions for the experienced.

Table of Contents

Python interview questions and answers for Freshers

1. What is Python?

Python is an interpreted, high-level, general-purpose, multi-paradigm programming language. One can use Python for:

  • Web application development
  • Desktop application development
  • Building Games
  • Data Science

2. What are the features or benefits of the Python programming language?

Python is highly adopted across companies, most preferred by data scientists, and arguably the 2nd most popular programming language. The reasons are:

  • easy to learn
  •  simple
  • easy to script
  •  open-source and free
  • Dynamically-typed
  • Interpreted
  • Fraught with libraries
  • Modular
  • And Rapid Application development

3. Explain what does dynamically-typed language means? Is Python one?

There are two types of typing in the programming languages – strongly-typed and weekly-typed programming languages.  Let’s understand what ‘typing’ refers to, here. 

Python is a strongly-typed language. This means that whenever the developer writes “6” + 3, an error message shows up in Python for it is a strongly-typed language. Python does not support type-coercion, which means implicit conversion of data types.

In case of JavaScript which is a weakly-typed language, the same “6” + 3 don’t throw errors but comes with a result of 63.

Now coming to the type-checking, again there are

  • Static: Data types – Checked before the execution of the program
  • Dynamic: Data Types – checked during the execution.

Python, which is an interpreted language, checks for errors during execution. Hence, Python falls into the category of dynamically-typed language.

4. What are Pep8 guidelines in Python?

PEP is an abbreviation for the Python Enhancement Proposal. Python.org has released an official communication document that describes any new feature introduced in Python or its processes, to the Python community.

PEP 8 is the official documentation of the style guidelines for Python coding.  This body expects the guidelines to be followed strictly and sincerely.

5. How does memory management take place in Python?

Python Memory Manager manages the memory management in Python. This memory manager assigns a Private Heap Space for Python that stores all Python objects. However, being a private space, this area is not accessible to the Python user.  However, using the core API functions, the Python programmer gets to use this private heap space.

Python Interview Questions
Python memory manager – Python Interview Questions

Python’s in-built garbage collector regularly frees up to vacate the unused memory space.

6. What is a namespace in Python?

Namespaces in Python are to ensure that there is no conflict when it comes to dealing with the object names in a Python program. Python makes the namespaces as a key-value pair, where object name is the key and object is the value.

This technique essentially enables multiple namespaces to make use of the same name and map it to different objects in Python program.

Local Namespace:  This includes all the local names of the objects within a function. This namespace is temporary in nature. It is created when the function calls for it and cleared once the function returns the value.

Global Namespace: This includes all the names of the objects used in the project and also the ones imported from various packages/modules. The global namespaces are created when a package is imported in the project and lasts until the execution of the script.

Built-in Namespace: These are the ones that include all the built-in functions and built-in names of exceptions in Python.

7. What are decorators in Python?

Decorators are essentially the callable objects in Python that are used to modify a Python function/method. The decorators are used to modify just the behavior of the function/method without changing the function as such.

#decorator function for converting to lowercase

def lowercase_decorator(function):
    def my_func():
       func = function()
        string_lowercase= func.lower()
        return string_lowercase
   return my_func

@lowercase_decorator #this is executed
def hello():
    return ‘I AM GOOD’

hello()

output:

'i am good'

8. Explain what are list and tuples? Explain the difference.

List and Tuples, both are data types in Python that can store an array of objects. Both the sequences can store objects of different data types. While the lists are represented by square brackets, [‘Freddie’, 6, 140], the tuples are represented using (), (‘Mini’, 8, 150).

The main difference between the list and tuples are that lists are mutable and tuples are immutable. In other words, one can modify, append, or slice down the lists. However, the tuples are immutable, meaning, they cannot be modified in any way.

Below is a small program to show the difference:

list and tuples - Python Interview Questions
list and tuples – Python Interview Questions

9. What are the most common built-in datatypes in Python?

In Python, there are several built-in data types. However, the advantage with Python is that the data types need not be declared explicitly. To know about the data type of a variable in Python, type() and isinstance() functions can be used.

Below is the list of built-in data types in Python:

Data TypeDescription
Numeric Types
IntStores all binary, hex, and octal numbers as integers
floatStores all literals containing decimal values
complexStores all complex numbers in a+bi form
BoolStores as True or False
Sequence Types
listStores different objects in a mutable sequence
TupleStores different object in an immutable sequence
RangeIt is an immutable sequence of numbers which is generated during execution
StrImmutable sequence to store textual data
Mapping Types
dictContains key, value pairs
Set Types
SetA mutable, but the unordered collection of separate hashable objects
Frozen SetImmutable collection of separate hashable objects

Modules: Modules are additional built-in data types supported by Python interpreter.

Callable Types: These are user-defined functions, built-in functions, methods and classes.

10. What is lambda in Python? How to use it?

Python’s lambda is an anonymous function that can take any number of arguments but can have only one expression. One can use Lambda when they require a function for a short period of time. Lambda can be used in two ways:

  • Using lambda to assign to a variable
my_var = lambda a,b:a*b
print(my_var(2,5))

output:

10
  • Using lamba within another function
def my_function(n):
    return lambda a: a*n
my_var = my_function(5)
print(my_var(2))

output:

10

11. What is pass in Python?

Just as the literal meaning of pass, the keyword suggests to do nothing but to perform a null operation. The keyword is used as a filling up technique when a block of code is being run at the time of execution. Not using the pass keyword however, might result in errors during the code execution.

def doNothingFunc():
   pass
doNothingFunc()    # output -> nothing happens

12.  Explain what are modules and packages in Python?

Python is supported by Python modules and Python packages that allows for Python’s modular approach in programming.

Modules: Python modules are essentially Python files with .py extension. They could contain a set of functions, variables, or even classes.  They can be included in the program by importing them using import keyword.

Packages: These are on the other hand is a hierarchical structuring on module namespace that uses the dot notation. These help avoid the conflict between the module names.

13.  Explain what are global, protected, and Private in Python?

Global variables: These are the variables which are declared using the keyword global. These are the public variables meant for global use within a project. Variables can be declared as global within a function.

Protected variables: These can be variables which can be accessed from outside a class; however, a responsible programmer should avoid doing that. The protected variables are ideally represented using _ (underscore) before the variable name. For example: _myVar

Private Variables: These are the variables in Python which cannot be used outside a class directly by the programmer. In case, the developer tries to access it from outside the scope of the private variable, the program essentially throws an AttributeError. The private variables are declared using the __(double underscores) in front of the variable name. Ex: __myVar.

14.  Explain the significance of ‘self’ keyword in Python.

Self keyword, like in Java, refers to an object of the class. However, unlike in Java where the usage of self is an option, it is mandatory in Python.

Self is ideally used to differentiate the methods and other attributes of the class from the local variables.

class Student:
    def __init__(self, fname, lname, age, height):
        self.firstname = fname
        self.lastname = lname
        self.age = age
        self.height = height
        print("The age and height of " + self.firstname + " " + self.lastname + " is: " + str(self.age) + " ,      " + str(self.height))

#creating the object
s1 = Student("Chris", "Whittaker", 8, 140.8)

Output:

The age and height of Chris Whittaker is: 8 , 140.8

15.  Explain__init__.

__init__ is a constructor in Python that is automatically called for memory allocation as soon as the object is created. __init__ constructor is mandatory for all classes.

Note: Refer to the example in Q14 for reference.

16.  What are the applications of Python?

Different applications of Python are:

  • Django ( A web framework of Python)
  • Flask and Bottle (Micro Frameworks)
  • Plone and Django CMS (For content management)

17.  What is pickling and unpickling in Python?

Python has a feature called serialization. Serialization enables a Python object to be stored in memory in a specific format. However, the object can be de-serialized to get the object back.

Pickling: Now, pickling is the name given to the serialization of the object. The Python objects are pickled into byte stream and then dumped into memory.  Ex: pickle.dump()

Unpickling: This process is a complete inverse of the pickling process. Unpickling de-serializes the object in the byte stream for normal use as it loads the object into memory. Ex: pickle.load()

18.  Explain PYTHONPATH in Python.

PYTHONPATH is an environment variable which should be set in order to make use of the modules and packages. It comes into use especially when the user defined libraries need to be used but are not yet installed in the global location.

19.  Explain the difference between .Py and .pyc  file extensions.

The main differences between the .py and .pyc files are:

  • While the .py files include the source code of a Python program, the .pyc file contains the byte code. We get the byte code only after the source code is run. Therefore, the .pyc files are formed when the .py files are run. However, there is a catch. Not all programs have a .pyc file. It is only created for the files that we import.
  • Right before a Python program is executed; the virtual machine looks for a compiled.pyc file. When it is not found, the virtual machine looks for .py file, compiles it into.pyc file. Then the virtual machine executes it.
  • The existence of .pyc file saves the compilation time.

20.  How is Python an interpreted language?

It is Python’s byte code which is interpreted.

  • The source code with .py extension is first compiled to form a byte code .pyc file.
  • The byte code is then interpreted using either the official CPython or Just in Time (JIT) compiler.

21.  What are unit tests in Python?

The unittest is a unit testing framework in Python.

  • Unit Testing is to test each component of the Python program separately to overcome the complete failure of the program.
  • Unit Testing enables to pinpoint the exact cause of failure.

22.  What are Python iterators?

Iterators in Python are objects. They are initiated by the __iter__() method. The iterators  are used to iterate over the sequential data types like lists and tuples.

23.  Explain the role of Split() and Join()in Python.

Split() – Split is a function in Python which splits a string based on a delimeter to a list of strings

Join() – Join is a function in Python which joins a list of strings based on the delimeter to form into a single string.

24.  Explain the difference between list and arrays in Python?

Arrays – Arrays in Python essentially store elements of the same data type. It is a homogeneous sequential data type. Arrays consume less memory space.

Lists – Lists on the other hand, can store elements of different data types. Lists consume more  memory space.

25.  What are negative indexes in Python? How to use them?

Negative index is a concept in Python through which the user can access the list, tuple, array, or string from the end.

It is denoted by [-1].

Ex:

My_List = ['chris', 'Mandela', 'carrrie', 'Shaw']
#To get the last element
print(My_List[-1])
#To get the second last element
print(My_List[-2])

Output:

Shaw
carrrie

26.  Explain what is docstring in Python?

A docstring in Python is used to document the functionality of a method or function. It is essentially a few lines of string.

27.  Explain what are *args and **kwargs in Python?

*args – It is syntax in Python used to specify the length of a variable that is passed as an argument in a function. Here * means the variable length and ‘args’ is used as a convention.

def product(a,b,*args):
    pro = a*b
    for i in args:
        pro *= i
    return pro
print(product(1, 2, 3, 4, 5))

output:

120

**kwargs – This is also a special syntax that is passed as an argument in a function. It contains a key, value pair where the key is the variable name and the value is the corresponding value you store in it.

def myExample(**kwargs):
    for key,value in kwargs.items():
        print(key + " : ",  value)
myExample(arg1=1, arg2=2, arg3=3)

output:

arg1 :  1
arg2 :  2
arg3 :  3

28.  Explain the main difference between Django, Pyramid, and Flask?

Flask – This is a” microframework” in Python which is essentially used for building smaller applications. All the libraries are included in Flask and it is ready to use.

Pyramid – This is a framework in Python which is used to build larger applications. The developers can include external tools such as they can choose the database, URL structure, and template style, etc. Pyramid can be configured.

Django – This is also meant for building larger applications. Django also includes Object-relational Mapping (ORM).

29.  Explain the Dogpile effect. How to prevent it?

Dogpile effect in Python is when the value in the cache expires and the website is hit with multiple requests at the same time.

This effect can be prevented using the Semaphore lock. If the value expires, the first process acquires the lock and a new value is generated. All the following requests check if the lock is intact and serve the old content. The lock is released once the new value is generated.

30.  What is the difference between ‘func’ and ‘func()’ ?

func – This is the object representing a function ‘func()’ that can be assigned or passed as an argument to another function.

func() – This calls a function ‘func()’ and returns a value.

31.  How does map function work in Python?

The map function takes a function and a sequence as arguments. It returns a map object each time as it iterates over the sequence. It returns values from applying that function to every element in the sequence. The map object can also be converted into a list.

Ex:

map function work - Python Interview Questions
Map function work – Python Interview Questions

32.  What is the job of reduce() in Python?

Reduce also takes a function and a sequence as arguments and iterates over the sequence. In every iteration, you pass both the current element of the sequence and the output of the function from the previous element to the function. The end value is a single output.

Ex:

reduce() - Python Interview Questions
reduce() – Python Interview Questions

33.  How does filter() work in Python?

Filter function does the job as the name suggests. It essentially filters elements in a sequence.

This function also takes two arguments, a function and a sequence. If you pass each element from the sequence into the function, then the function returns a Boolean value – True/False. The sequence value is discarded if the function returns False and included if it is True.

Ex:

filter() work - Python Interview Questions
filter() work – Python Interview Questions

34.  How to concatenate two arrays in Python?

First off, arrays are from NumPy. We can simply use NumPy’s concatenate () function to join two arrays.

import numpy as np
arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])
np.concatenate((arr1,arr2))

output:

array([1, 2, 3, 4, 5, 6])

35.  Give examples of mutable and immutable objects in Python.

Mutable Objects – These are the objects that you can modify, change, or append after creating them. Ex: list, set, and dict.

Immutable Objects – These are the objects which you cannot change or modify after the creation. Ex: int, float, bool, string, tuple.

36.  How to delete a file in Python?

One can delete a file using :

import os
os.remove("My_File.csv")

Python interview questions and answers for Experienced

37.  What is Scope in Python?

All the objects in a Python function are within scope. The scope is where the objects remain relevant.

  • Local Scope – This refers to local objects within a function
  • Global Scope – These are the objects that remain relevant throughout the program since its inception.
  • Module-level scope – They refer to the objects in the program, used in relevance to the module.
  • Outermost scope – This refers to all the built-in names callable in a program.

38.  What do you mean by Scope Resolution in Python?

Sometimes objects in different scopes have the same names and have different functionality. This can cause ambiguity. You can resolve this issue in Python using Scope resolution.

For example the two modules ‘math’ and ‘cmath’ have many common named functions such as log10(). The users can prefix the function using the module name to overcome the ambiguity.

Ex: math.log10(), cmath.log10()

Ex:

Python Interview Questions and answers
Scope Resolution in Python – python interview questions

39.  Explain Dict and List comprehensions. How can you use them?

One uses Python comprehensions to build altered functionalities to objects like lists, dictionaries, or sets. Comprehensions save time and coding and can be considered beneficial in many aspects.

Ex:

L_list = [2,3,4,5]
cubed_list = [x**3 for x in L_list]    # list comprehension
print(cubed_list)# output => [8 , 27 , 64 , 125]
cubed_dict = {x:x**3 for x in L_list}    # dict comprehension
print(cubed_dict)# output => { 2: 8 , 3: 27 , 4: 64 , 5: 125}

40.  How to copy an object in Python?

In Python, a simple ‘=’ does not create a duplicate of the object. We can copy objects in 2 ways:

Shallow copy: This is a bit-wise copy. The duplicate object is the exact same as the actual object. It first creates a new object and then inserts the references into it. One can perform this using copy().

Deep Copy: A copy formed recursively from the actual object to the duplicate object. This method duplicates the original and recursively inserts the references into it. One can achieve this using deepcopy().

41.  Explain the difference between range and xrange in Python.

Most of the times, the range and xrange are same in terms of functionality.

The difference is essentially that while range returns a Python list, the xrange returns xrange object.

42.  What are break, continue, and pass in Python?

Break:

One use the break keyword to break the current loop or statement in which it is present. The code after the break statement will start executing.

#Python program to demonstrate the use of break
word = "pradtutorials"
for letter in word:
    print(letter)
    if letter == 'd':
       break
print("Out of for loop")       

output:

p
r
a
d
Out of for loop

Continue:  

This is also a loop control statement but does the opposite of the break statement. Instead of terminating the loop, the continue keyword forces the execution of the next iteration of the loop.

# Python program to demonstrate the use of continue
# loop from 1 to 10
for number in range(1, 11):
    # If i is equals to 5 continue to next iteration without printing
    if number == 5:
        continue
    else:
        print(number)
1
2
3
4
6
7
8
9
10

Pass:

Just as the name suggests, the pass keyword does nothing. One can use this when the syntax needs a loop/statement, however, requires no action as such. It is similar to a null operation.

# Python program to demonstrate the use of pass

word = "pradtutorials"
# Empty loop
for i in word:
    # Nothing happens
    pass

# Empty function
def fun():
    pass
# Nothing happens
fun()

# Pass statement
for letter in word:
    if letter == 't':
        #Pass executed
        pass
    print(letter)

Output:

p
r
a
d
t
u
t
o
r
i
a
l
s

43.  What are generators in Python?

Generators are nothing but functions which return an iterator which we can iterate over it again.

import random
def example():
    # returns 6 numbers between 1 and 50
    for i in range(0,6):
        yield random.randint(1, 50)
for number in example():
       print("And the next number is... %d!" %(number))

Output:

And the next number is... 2!
And the next number is... 44!
And the next number is... 43!
And the next number is... 15!
And the next number is... 47!
And the next number is... 1!

44.  One can pass arguments in Python – by value or by reference. Explain.

In Python, all the arguments you pass are by reference. It means if one makes a change to the argument, it reflects in the calling function.

45. How can you make Python Script executable in Unix?

On the Unix systems, one can execute Python scripts by using the following process:

  • Add this line as the first line in the script:

# !/usr/bin/env python3.

  • At the Unix command prompt, type the following to make myscript.py executable:

$ chmod +x myscript.py

  • Move myscript.py into your bin directory, and it will be runnable from anywhere.

The ideal way to share the global variables across modules is by creating a config module. Now, importing the config module in all modules make it globally available.              

47.  How can you access the module written in Python from C?

One can get a pointer to the module by calling:

module = PyImport_ImportModule(“mymodule”)

48.  Explain the database connection in Python Flask.

Flask supports RDBS. Hence, it requires creating a schema. First, one can install the SQLite3 module in order to initiate the database connection in Flask. Then, schema.sql file has to be piped into the sqlite3.

49.  How can you minimize the Memcached server outages in Python development?

There are several ways about which one can minimize the Memcached server outages.

  • One way is to create an instance of Memcached on another machine using the IP address of the lost machine.
  • Setting a time-out value is one way of minimizing server outages. When the Memcached server goes down, the client will keep sending the requests until it reaches the timed-out value.
  • Coding is another option to control the server outages.

50.  Let’s say you have numerous Memchache servers running in Python and one of them fails. It has your data. Will it ever try to retrieve data from the failed one?

The data in the failed server will not be removed. In fact, there is a provision for auto-failures that you can configure for multiple nodes.

Leave a Comment

Pin It on Pinterest