Python Interview Questions

Here are the top Python interview questions and answers that cover a wide basic level topics associated with Python such as pickling and unpickling, slicing, basic types of functions available in Python, ways to convert a string to a number in Python, whitespaces in Python and advanced level topics like iterators, generators, decorators, rstrip() function in Python. Go through these Python interview question-answer sets and land your dream job as a Python Developer, Full Stack engineer, and other top profiles. Practice these interview questions on Python with answers provided by experts and be fully prepared for your next Python interview.

  • 4.5 Rating
  • 100 Question(s)
  • 50 Mins of Read
  • 9645 Reader(s)


Some of the features of Python are -

  1. Simple and Minimalistic: Python is a high-level language but it is quite like reading English. You can easily understand what the code is supposed to do. Also, since it is dynamically-typed, it mandates indentation. It becomes simple to read.
  2. Easy to Learn: Python has an extraordinarily simple syntax, which makes it extremely easy to learn. It is developer-friendly.
  3. Cross-platform Language: Due to its open-source nature, Python is portable. Python programs can work on almost all platforms such as Windows, Mac OS, Linux and so on without requiring any changes at all if you are careful enough to avoid any system-dependent features.
  4. Interpreted: While we use languages like C++ or Java, we have to first compile it and then run it, whereas, in Python, the source code is first converted into an immediate form called bytecode. So, there is no need to compile. The Python code simply needs to be run without worrying about linking to libraries. When we say interpreted, we mean the source code is executed line by line, and not the entire code at once. It gets easier to debug your code. Though interpreting makes it just slightly slower than Java, that does not matter compared to the benefits it has to offer.
  5. Object Oriented: Python is a multi-paradigm programming language. We can either build the program around procedures/functions or we can build a program around objects which combine data and functionality.
  6. Extensible: It means we can use other languages such as C/C++ to compile the code and further use it in our Python code.
  7. Embeddable: We have seen that we can use other languages such as C/C++ to compile the code and then use it in our Python code, similarly, we can also use Python code in source code in C++ or any other languages. This feature allows us to integrate scripting capabilities into our program of the other language.
  8. Extensive Library: Python has a large and broad library and provides a rich set of modules and functions. The programmer does not have to write a code for everything. Libraries are available for regular expressions, web browsers, threading, machine learning algorithms and so on.
  9. Dynamically Typed: In Python, we do not need to specify the type of value while declaring it, the type of value is decided at runtime.

Pickling can be used in Python to pickle an object so that it can be saved on disk. Basically, pickling is a process to convert a python object (list, dict, etc.) into a character stream using a pickle module. Pickling “serialises” the object first before it writes it to file.

There are two types of pickling method -

  1. Dump is the method which dumps an object to a file object,
  2. Load is the method which loads an object from a file object.

On the other hand, unpickling is the reverse process. It retrieves the stored string and converts it back into an object.

Slicing in Python is a process that can be used to select a range of items from Sequence types such as strings, list, tuple and so on.

The slice() constructor simply creates a slice object representing the set of indices specified by range(start, stop, step).

In Python, slice() accepts three parameters which means the same in both constructs:

  • start - starting integer where the slicing of the object begins
  • stop - integer until which indicates the end of slicing. The slicing stops at index stop - 1.
  • step - the integer value to increment after each index (default = 1)

Suppose, a single parameter is passed then, start and step are set to None.

For example - To create a slice object for slicing

# contains indices (0, 1, 2)

# contains indices (1, 3)
print(slice(1, 5, 2)

After you run the program, you will get the following output.

slice(None, 3, None)
slice(1, 5, 2)

This is how a generator function differs from a normal function.

  • There is one or more yield statement in general function
  • When a generator function is called, it does not start execution immediately instead returns an object (iterator)
  • We cannot iterate through items using next() as methods like __iter__() and __next__() are implemented automatically
  • As soon as the function yields, the function is paused and the control is passed on to the caller
  • Between successive calls, local variables and their states are remembered
  • Lastly, when the function terminates, on further calls StopIteration is raised automatically.

Python is an object-oriented programming language. OOP concept means that we can solve a problem in Python by creating an object model in our program. Some of the features of object-oriented programming are inheritance, polymorphism, abstraction, encapsulation.

Python uses range() function which generates a list of numbers and is used to iterate over loops.

for i in range(5):

The two set of parameters are accompanied by the range() function.

  • range(stop)
    • stop: number of integers to be generated and it starts from zero. For example, range(4) == [0,1,2,3,4]
  • range([start], stop[, step])
    • Start: It indicates the starting no. of the sequence.
    • Stop: It indicates the upper limit of the sequence.
    • Step: It indicates the incrementing factor for generating the sequence.
print sum(range(10,101))
#range() returns a list to the sum function containing
#all the numbers from 10 to 100. Please see that
#the range function does not include the end given (101 here).

print(sum(xrange(10, 101)))
#xrange() returns an iterator rather than a list
#which is less heavy in the memory.

Python provides us with two basic types of functions:

  1. Built-in functions, such as print(), dir(), len() etc.
  2. User-defined functions

PEP stands for Python Enhancement Proposal. It is mainly used to maintain specific standards. PEP 8 is one of Python’s style guide and it is a set of rules which are followed to format Python code for maximum readability. Writing code using specific standards helps us to make large code bases, as well as other coders, can contribute to it easily and it turns out to be uniform too.

The <int()> method provided by Python, is a standard built-in function which converts a string into an integer value.

It can be called with a string containing a number as the argument, and it will return the number converted to an actual integer.

print int("1") + 2
The above prints 3.

The most commonly used built-in types which Python support are -

  • Immutable data types
    • Tuples
    • Numbers
    • Strings
  • Mutable data types
    • Sets
    • List
    • Dictionaries

In Python, whitespaces are the character used for spacing and separation. It has an ‘empty’ representation. In the context of Python, whitespace can be a tab or space.

The whitespace characters can be used interchangeably to separate tokens except at the beginning of a logical line or in string literals. Whitespace is a must between two tokens if there is concatenation else it can be interpreted as a different token. For example, “ab” is one token whereas “a b” are two tokens.

A function in Python can be created in the steps mentioned below:

Step 1: To start with the function, declare the function by writing the keyboard def followed by the function name.

Step 2: Now write the arguments inside the open and close parentheses of the function, and end the declaration with a colon.

Step 3: Next, add the program statements which needs to be executed.

In Python, when the argument whether a value or an expression gets bound to a respective variable in the function it is said to be “Call by Value”.

Python treats that variable as local and any changes made to that variable remains local and does not reflect outside the function.

In Python, both “call by reference” and “pass by reference” are used interchangeably. When an argument is passed by reference, it is then available as an implicit reference to the function instead of a simple copy. If any modification is made to the argument, it will also be visible to the caller.

The advantage of this is that it brings in more time and space efficiency there is no need to create local copies.

On the other hand, the disadvantage is there could be a situation when a variable gets changed accidentally during a function call. To avoid such cases, the programmer needs to look into the code.

In Python, the default print() function ends with a newline. The print() function comes with a parameter called ‘end’ and the value of this parameter in ‘/n’ which means a new line. A print statement can be ended with any character/string using this parameter. Using this parameter, we can change the end character in the print statement according to our choice.

For example, in print a line instead of the new line in the end:

print("Let us learn" , end = ' ')  

# Printing a dot in the end.
print("knowledgehut" , end = '.')  
print("com", end = ' ')

The output is

Let us learn Python

In Python, there are two types of errors - syntax error and exceptions.

Syntax Error- It is also known as parsing errors. Errors are issues in a program which may cause it to exit abnormally. When an error is detected, the parser repeats the offending line and then displays an arrow which points at the earliest point in the line.

Exceptions- Exceptions take place in a program when the normal flow of the program is interrupted due to the occurrence of an external event. Even if the syntax of the program is correct, there are chances of detecting an error during execution, this error is nothing but an exception. Some of the examples of exceptions are - ZeroDivisionError, TypeError and NameError.

The key difference between lists and tuples is the fact that lists have mutable nature and tuples have immutable nature.

It is said to be a mutable data type when a python object can be modified. On the other hand, immutable data types cannot be modified. Let us see an example to modify an item list vs tuple.

list_num[2] = 5

tup_num[2] = 5


Traceback (most recent call last):
File "python", line 6, in <module>
TypeError: 'tuple' object does not support item assignment

In this code, we had assigned 5 to list_num at index 2 and in the output, we can see 5 is found in index 2. However, we had assigned 5 to tup_num at index 2 but we got type error on the output. This is because we cannot modify tuples due to its immutable nature.

A module is a Python object which contains an arbitrarily named ‘attributes’ that you can bind. Python modules are basically files which contain Python codes. This code can define variables, functions or classes. It allows you to organize your Python code logically. It can also include runnable code.

Some of the commonly used built-in modules in Python are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

Global Variables - The variables which are declared outside a function are called global variables. Such variables can be accessed by any function in the program.

Local Variables - The variables which are declared inside a function are known as local variables and such variables are present in the local space and not in the global space.

For example:

a=4 #global variable
def add():
b=6 #local variable
print c



In Python, type conversion is used to directly convert one data type to another. Some of the data types are mentioned below:

It converts any data type into integer type
It converts any data type into float type
It converts characters into an integer
It converts integers to hexadecimal
It converts an integer to octal
It is used to convert to a tuple
It is used to return the type after converting to set
It is used to convert any data type to a list type
It is is used to convert a tuple of order (key, value) into a dictionary
It is used to convert an integer into a string
It converts real numbers to complex(real,imag) number

Indentation is important in Python. It indicates a block of code. Anything within loops, functions or classes etc. is specified within an indented block. Indentation is generally done using four space characters, if the code is not properly indented, the execution will not be accurate and will also show errors.

Numpy Arrays
NumPy is more efficient and more convenient.  A lot of vector and matrix operations are available and they can be efficiently implemented.
Lists in Python are efficient general purpose containers. It supports efficient insertion, deletion, concatenation and appending. Lists make it easier to construct and manipulate.
NumPy is fast and a lot of built-in functions are available such as FFTs, convolutions, statistics, linear algebra, histogram etc.
Lists have certain limitations as they do not support “vectorized” operations such as element-wise addition and multiplication and also the fact that it contains different types of objects

The main difference between Pass and Continue is that the continue statement allows the loop to resume from the next iteration. On the other hand, the pass statement does nothing and the remaining code is executed as usual.

An index in Python is an integer data type which basically denotes a position within an ordered list or a string. In Python, strings are considered as a list of characters and we can get access to each character using the index which begins from zero and ends with the length minus one.

In Python, the len() function is used to determine the length of an input string. It is a primary string function which can be used to calculate the number of characters present in a string.

For example,

str_name = 'learning'

The output will be -


In Python, comments are written using the # character. Alternatively, comments can be written using docstrings (strings enclosed with triple quotes).

For example:

#Comments in Python starts with the hash character
print("Comments in a Python code start with a #")


Comments in a Python code start with a #

In Python, a lambda function is an anonymous function which can have any number of parameters but should contain only one statement.

For example:

a = lambda x,y : x+y
print(a(3, 9))



In order to convert a string to lowercase, the function lower() can be used.

For example:




In Python, docstrings are not really comments but are documentation strings. They can be used as comments. It is denoted within triple quotes. Docstrings are not assigned to any variable and therefore serves the purpose of comments as well

For example:

Using docstring as a comment.
This code divides 2 numbers



In Python, a dictionary is a built-in datatype. It defines a one-to-one relationship between keys and values. Each pair of keys have their corresponding values. They are indexed by keys.

For example,

Consider some key and value pairs such as Name, Age and Blood group (BG).

dict={'Name' : 'James', 'Age' : '25' : 'BG' : 'A+'}
print dict[name]
print dict[Age]
print dict[BG]

Firstly, import OS module and then use os.remove() function in order to delete files in Python.

For example:

import os

The main differences between lambda and def are mentioned below -

It is a uni-expression function.
It can hold multiple expressions.
It forms a function object and returns it.
It generates a function and designates a name to call it.
It cannot return statements.
It can have a return statement.
It can be used inside a list and dictionary.
It does not support to get used.

In Python, sequences are indexed with both positive and negative numbers. The positive numbers use ‘0’ as the first index and ‘1’ as the second index and so on.

Similarly, the index for the negative number starts from ‘-1’ which represents the last index in the sequence and ‘-2’ as the penultimate index and it goes on just like the positive numbers.

The negative index helps in the removal of the new-line spaces from the string and it can also be used to show the index to represent the string in the correct order.

Encapsulation is the process of binding the code and the data together. An example of encapsulation would be a Python class.

Python does not support multiple inheritances as Java does. Multiple inheritances mean that from more than one parent classes a class can be derived.

Polymorphism is the ability to take multiple forms. Suppose if the parent class has a method named XYZ then the child class can have the same name with its own variables and parameters. Python supports polymorphism.

Data Abstraction allows you to provide only the required details and hides the implementation from the world. It can be easily achieved in Python by using interfaces and abstract classes.

Python lays down a convention of prefixing the name of the method/variable with a single or double underscore to emulate the behaviour of protected and private access specifiers. All the members in a Python class are public by default. Also, any member can be accessed from outside the class environment.

In Python, the class keyword is used to create a class.

For example:

class Stduent:
def __init__(self, name): = name



An object() returns a featureless object which is a base for all classes. It does not consider any parameters.

In order to reverse a list, use list.reverse() − it reverses objects of the list in place. The reverse() function doesn't return any value. The elements are reversed and the lists are updated.

# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)

# List Reverse

# updated list
print('Updated List:', os)


Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']

NumPy is a Python library which is written in C and therefore is one of the fastest and most compatible libraries among the rest. It is a basic library for mathematical or numerical calculation. Some of the basic operations are indexing, reshaping, indexing etc..

On the other hand, SciPy stands for scientific Python and has been written on the top of NumPy. Some of the operations include: Special functions (scipy.special), Integration (scipy.integrate), Optimization (scipy.optimize), Interpolation (scipy.interpolate), Fourier Transforms (scipy.fftpack), Signal Processing (scipy.signal), Linear Algebra (scipy.linalg), Statistics (scipy.stats).

Python supports:

   ‘+’    : Addition

   ‘-’    : Subtraction

   ‘*’   : Multiplication

             ‘/’ : Division

             ‘%’ : Modulo division

             ‘**’ : Power Of

             ‘//’ : floor div

Python also supports augmented assignment operators such as -

A += 5 means A = A + 5

B -= 7 means B = B - 7

Some other operators Python support are & , |, ~ , ^ which are and, or, bitwise complement and bitwise xor operations.

Python does not support unary operators such as ++ or - operators.

  1. Numeric Datatypes: int, long, float, NoneType
  2. String: str
  3. Boolean: (True, False)
  4. NoneType: None

Python allows us to handle loops in an interesting manner by providing a function to write else block for cases when the loop does not satisfy a certain condition.

For example :

x = [ ]
   for i in x:
       print "in for loop"
        print "in else block"


in else block

It works in a similar manner with while-else.

In Python, the tuple() function can be used to convert a list into a tuple. As tuples are immutable, we cannot change it back to a list.

For example:

days = ['sun','mon','tue','wed','thu','fri','sat']
listtoTuple = tuple(days)


('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')

In Python, set() function can be used to convert a list into a set.

For example:

days = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listtoSet = set(days)


set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])

In the Python list, we can use the count() function to count the occurrences of an individual element.

Example # 1:

days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue', 'tue']



Example # 2:

days = ['sun','mon','tue','wed','thu','fri','sun','tue','tue']
print([[x,days.count(x)] for x in set(days)])


[['wed', 1], ['sun', 2], ['thu', 1], ['tue', 3], ['mon', 1], ['fri', 1]]

Some of the most used text processing methods are mentioned below:

a = 'hello world'
a.upper()    #Converts to Uppercase

a.lower()    #Converts to Lowercase
'hello world'

a.capitalize()    #First Letter is capitalized.
'Hello world'

a.title()    #First character of the every word is capitalized.
'Hello World'

a.split()    #Splits based on space and returns a list. Split takes an optional parameter to split. By #default it considers space based on which it splits
['hello', 'world']

record = 'name:age:id:salary'    #Splitting based on ':'
['name', 'age', 'id', 'salary']

a = '\n\t    hello world \t\n'
print a
hello world
a.strip()    #strips leading and trailing white spaces and newlines.
'hello world'

a.lstrip()    #left strip
'hello world \t\n'

a.rstrip()    #right strip
'\n\t\thello world'

a = 'hello'
a.isalpha()    #returns true only if the string contains alphabets.

a = 'hello world'    #As there is a space, it returned false.

a = '1234'
>> a.isdigit()    #Returns True only if the string contains digits.

a = '1234a'
a.isdigit()    #returned false as the string contains a alphabet

a.isalnum()    # returns true if the string contains alphabets and digits.

a = 'Name: {name}, Age: {age}'
a.format(name='Harry', age='22')
'Name: Harry, Age: 22'

In python, we have a method called update() which can be used in order to merge one dictionary on another.

For example:

a = {'a':3}
b = {'b':2}


{'a': 3, 'b': 2} 

In Python, all functions and variables follow lowercase and underscore naming convention. For example,

is_prime(), test_var = 30 etc.

However, constants are either camelcase or uppercase. For example,

Max_val = 20, PI = 3.14

Even for class names, camelcase is followed. For example,


  • TypeError- It occurs when the expected type does not match with the given type of a variable.
  • ValueError- It occurs when an expected value is not given, suppose you are expecting 6 elements in a list and you gave 2.
  • NameError- It occurs when you are trying to access an undefined variable or a function.
  • IOError- It occurs when you are trying to access a file that does not exist.
  • IndexError- It occurs when you are trying to access an invalid index of a sequence.
  • KeyError- It occurs when you use an invalid key to access a value in the dictionary.

In Python, the sys module gives the version of Python being used. The code mentioned below shows how to check for the version.

import sys

In order to get the list of all the keys in a dictionary, use function keys(). For example,

dict_keys(['a', 'b', 'c', 'e']) 
def f(x,l=[]):
   for i in range(x):


The output will be:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

Some of the additional data structures are -

  1. Bisect
  2. Boolean
  3. Deque
  4. Float
  5. Heapq
  6. Integers

The code mentioned below can be used to save an image locally from an URL address.

import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")

Random numbers can be generated by using various functions in Python. They are -

  1. random() – It returns a floating point number, between 0 and 1.
  2. uniform(X, Y) – It also returns a floating point number which lies between the values given as X and Y.
  3. randint(X, Y) – It returns a random integer which lies between the values given as X and Y.

In Python, to find the type and identification number of an object, we can use the functions type() and id().

type(<variableName>) - It gives us the type of the object that variable is pointing to.

id(<variablename>) - It gives us the unique identification number of the object that variable is pointing to.


In Python, an iterator is an object which can be iterated upon. It is an object which will return data, only one element at a time. Python iterator should implement two special methods, __iter__() and __next__(), which are collectively known as iterator protocol.

Most of the built-in containers in Python such as list, tuples, string etc. are iterables and an object is called iterable only if we can get an iterator from it. The iter() function returns an iterator from them.

mytuple = ("alice", "bob", "charlie")
myit = iter(mytuple)


In Python, a generator is a type of function which allows us to specify a function which acts as an iterator and therefore can be used in a ‘for’ loop. In a generator function, the yield keyword replaces the return statement.

# Simple Python function
def fn():
   return "Simple Python function."

# Python Generator function
def generate():
   yield "It is a PG function."


The output is:

It is a PG function.

In Python, decorator allows us to add new behaviour to the given objects dynamically. In the example below, a simple program shows how to display a message pre and post the execution of a function.

def deco_sample(func):
   def deco_hook(*args, **kwargs):
       print("Before the function is called")
       result = func(*args, **kwargs)
       print("After the function is called")
       return result
   return deco_hook

def product(x, y):
   "Function to multiply two numbers."
   return x * y

print(product(6, 6))

The output is:

Before the function is called
After the function is called

In Python, we can use two approaches in order to copy an object, Shallow Copy and Deep Copy.

Shallow Copy- In this approach, a new object is created which stores the reference of the original elements. A shallow copy simply copies the reference of nested objects and do not create a copy of nested objects.

For example,

import copy

list_old = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list_new = copy.copy(list_old)

print("Old list:", list_old)
print("New list:", list_new)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Deep Copy- In this approach, a new object is created and it recursively adds the copies of nested objects which are present in the original elements. In the example below, we will create a deep copy using deepcopy() function which is present in the copy module.

For example,

import copy

list_old = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
list_new = copy.deepcopy(old_list)

print("Old list:", list_old)
print("New list:", list_new)
Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

The main() function is said to be the entry point of a program, which is called first in most of the programming languages. In Python, the interpreter first executes the source file code in a sequential manner and do not call any method if it isn’t part of the code. However, if it is directly a part of the code then it is executed while the file is imported as a module.

To define this main method, there is a special technique used so that it is executed only when the program is run directly and not when it is imported as a module. A simple example mentioned below shows how to define python main function.

print("__name__ value: ", __name__)
def main():
   print("Print the main function")
if __name__ == '__main__':

The output:

__name__ value:  __main__
Print the main function

In Python, the rstrip() function can be used to duplicate the string but it leaves out the whitespace characters from the end. This function excludes the characters from the right end as per the argument value i.e, a string mentioning the group of characters to get excluded.

The signature of the rstrip() is:

str.rstrip([char sequence/pre>

For example,

str_name = 'Python'
#The white spaces are excluded

To handle Exceptions, Python provides constructs such as Try, Except, Finally. The unsafe code is indented under the Try block and then the fall-back code is kept inside the Except block. Lastly, any kind of instructions intended for execution comes under the Finally block.

   print("Executing code in the try block")
   print("Entering in the except block")
   print("Reached the final block")

The output is:

Executing code in the try block
Entering in the except block
Reached the final block 

In Python, globals() function returns the current global symbol table as a dictionary object. To keep all necessary information about a program, python maintains a symbol table. The information in this table remains in the global scope of the program and we can retrieve it by using the globals() method.

For example:

x = 8
def fn():
   y = 7
   z = y + x
   # Calling the globals() method
   z = globals()['x'] = z
   return z
# Test Code    
ret = fn()

The output is:


In Python, closures are function objects which are returned by another function. It is used to eliminate code redundancy.

In the example below, it shows a simple closure for multiplying numbers

def multiply_number(num):
   def product(number):
       'product() here is a closure'
       return num * number
   return product

num_2 = multiply_number(3)

num_6 = multiply_number(6)

The output is:


The pass statement is the statement which is a null operation. No operations take place when the pass statement is executed. It results in no operation (NOP). Python statements are case sensitive, so you should always write “pass” in lowercase, if you write “Pass”, an error will be shown: “NameError: name Pass is not defined.”

For example,

# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:

The optional statements that can be used in the try-except block are-

  • The “else” clause

It is used if you would like to run a piece of code when the try block does not create an exception.

  • The “finally” clause

It is used when you would like to execute some steps which run irrespective of whether an exception occurs or not.

*args is used as a parameter in the function header. It allows us to pass N (variable) number of arguments. However, it does not allow passing a named argument to the function.
For example, let us see a python code to demonstrate *args for dynamic arguments.

def fn(*argList):  
   for argx in argList:  
       print (argx)
fn('Let', 'Us', 'Learn', 'Python')

The output:


The split() function can be used to separate large strings into smaller ones or rather sub-strings. We can either use a separator for the split else it will use the space as one by default.

For example,

str_name = 'alice bob charlie'
str_name.split(" ")

The output will be -

['alice', 'bob', 'charlie']
['alice', 'bob', 'charlie']

title() method can be used to convert the first letter in each word to capital (uppercase) and the rest turns to lowercase.

For example,

str_name = 'cOnTInuOus lEarnIng'

The output will be -

Continuous Learning

Iterable is a type of object which would generate an Iterator when passed to in-built method iter()

For an object to be iterable, the class of the object needs to define two instance methods:  __len__ and __getitem__. Such an object, when passed to method iter(), would generate an iterator.

Iterator is the object which is used to iterate over an iterable object. It provides __next__ method to do so. The __next__ method is implicitly called when we use it in for loop.

In Python, lists and arrays store data in a similar manner. However, arrays hold only single data type elements whereas lists can hold any data type elements.

For example:

import array as arr


array('i', [1, 2, 3, 4]) [1, 'abc', 1.2]
  • Break - It allows you to terminate a loop when some condition is true, the control is transferred to the next statement.
  • Continue - It allows you to skip some part of the loop and certain condition is true, the control is transferred to the beginning of the loop.
  • Pass - It is used to when you want to skip an execution and want some block of code syntactically. It is basically a null operation. No operation (NOP) takes place when it is executed.

In order to reverse the order of an array we can use [::-1]

For example:

import array as arr


array('i', [5, 4, 3, 2, 1])

Operators are considered to be special functions. They accept one or more than one values and produce a corresponding result.

is: It returns true when 2 operands are true  (Example: “a” is ‘a’)

not: It returns the inverse of the boolean value.

in: It checks if some element is present in some sequence

Both the functions, help() and dir() can be accessed from the Python interpreter and is used to view a consolidated dump of built-in functions.

help() function - It is used to display the documentation string and it also facilitates you to check the help related to keywords, modules or attributes etc..

dir() function - It is used to display the defined symbols.

In order to add values or elements you can use functions like append(), extend() and the insert (i,x).

For example:

a=arr.array('d', [1.1 , 2.1 ,3.1] )


array('d', [1.1, 2.1, 3.1, 3.4])
array('d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])
array('d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])

In order to remove values or elements, we can use pop() and remove() methods. The main difference between these two functions is that pop() function returns the deleted value and remove() function do not.

For example:

a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])


array('d', [2.2, 3.8, 3.7, 1.2])

We can calculate percentiles with the following code

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) #Returns 50th percentile, e.g. median


A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]

The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

To get the indices of N maximum values in a NumPy array you can use the below code:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])


[ 4 3 1 ]

In order to sort a list in Python, the following code can be used :

list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
print (list)
a=input("enter a sequence")
if a==b:
print("Not a Palindrome")


enter a sequence 656 palindrome
a=int(input("enter a number"))
if a>1:
  for x in range(2,a):
          print("not prime")
  print("not prime")
for x in range(2,a):
print("not prime")


enter a number 3
# Enter number of terms needed #0,1,1,2,3,5....
a=int(input("Enter the terms"))
f=0 #first element of series
s=1 #second element of series

if a<=0:
print("The requested series is\n",f)
print(f,s,end=" ")
for x in range(2,a):
print(next,end=" ")


Enter the terms 5 0 1 1 2 3
def bs(a): # a = name of list
b=len(a)-1 # minus 1 because we always compare 2 adjacent values
#number of rounds will be 1 less than the total length of the list
for x in range(b):
for y in range(b-x):
if a[y]>a[y+1]:
return a


[2, 3, 4, 5, 46, 68, 92]
def list_sum(list_num):
if len(list_num) == 1:
return list_num[0]
return list_num[0] + list_sum(list_num[1:])
print(list_sum([3, 8, 2, 4, 5]))



A class which do not have any code defines within its block is known as an empty class. An empty class can be created using a pass keyword. However, objects can be created outside the class itself.

For example-

class x:
print("Name = ",


Name =  abc

In Python, memory management involves a private heap of Python objects and data structures. The interpreter takes control of Python heap and the developer does not have access to it.

Allocation of heap space for Python objects is assigned by the Python memory manager. There are certain tools provided by the core API of Python which helps to code reliable and more robust program.

Python has a built-in garbage collector, all the unused memory is recycled here. The GC module can be enabled and disabled by using defined functions-

gc.enable () - It enables the garbage collector for automatic garbage collection

gc.disable() - It disables the garbage collector for automatic garbage collection.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = (i for i in a if i%3 == 0)    #Generator expression.
for i in b: print i,

0 3 6 9 

The term monkey patch refers to dynamically modifying a class or module at run-time. In Python, we change the behaviour of code at run-time. Let us look into an example to understand in a better way.

class A:
    def func(self):
         print "Calling func()"

In the above code, we created a module and will be using later in order to change the behaviour of func() at run-time by assigning various values.

import monk
def monkey_f(self):
    print "monkey_f() is being called"
# replacing the address of "func" with "monkey_f"
monk.A.func = monkey_f
obj = monk.A()
# calling function "func" whose address got replaced
# with function "monkey_f()"


monkey_f() is being called

A class is also called the child/derived/subclass inheriting from the parent/base/superclass when it inherits. It inherits all attributes and methods from another class.

Inheritance allows us to reuse our code and make it simpler to create and maintain applications. Python supports -

  1. Single Inheritance- Parent is a single base class.
  2. Multiple Inheritance- Parent is a multiple base classes.
  3. Multilevel Inheritance- Parent is a base class, which, in turn, inherits from another base class.
  4. Hierarchical Inheritance- Parent is a single base class which leads to Multiple classes.
  5. Hybrid Inheritance- It is a combination of two or more than two types of inheritance.

A higher order function returns a new function by accepting one or more functions as input. In order to make high order functions, we will have to first import functools module. Functions like functools.partial() is often used for high order function. The functions act on or else return the other functions. For this particular module, the callable object can be treated as a function.

Python libraries are a collection of Python packages. Some of the majorly used python libraries are –Numpy, Pandas, Matplotlib, Scikit-learn and many more.

  • Numpy - NumPy is a library for the Python programming language which supports large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
  • Pandas -Pandas is a software library written for the Python programming language for data manipulation and analysis.
  • Matplotlib - Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy.
  • Scikit-learn - Scikit- learn is a free software machine learning library for the Python programming language. It features various classification, regression and clustering algorithms including support vector machines, etc.

In Python, we can use other numbering systems apart from decimal such as binary, octal, and hexadecimal.

  1. Binary numbers contain 0s and 1s. To type in binary, use prefix 0b or 0B. For example, int (0b1010) it will give an output 10In order to convert a number into its binary form, use bin() bin(0xf)
  2. Octal numbers contain 0 to 7. Use prefix 0o or 0O. For example, oct(8) will give an output ‘0o10’
  3. Hexadecimal numbers contain digits from 0 to 15. Use prefix 0x or 0X. For example, hex(16) will give an output ‘0x10’

In Python, the enumerate() function is used to add a counter to an iterable object. enumerate() function accepts sequential indexes starting from zero.

For example,

subjects = ('Python', 'Java', 'C++')
for i, subject in enumerate(subjects):
print(i, subject)


0 Python
1 Java
2 C++


It’s the time to acquaint you with the questions which you might face during your interview and will help you to crack Python interview easily & pursue your dream career.

Python has turned out to be the most in-demand programming language in recent years. Many IT  companies that hunt for good Python programmers are ready to pay the best salaries to the eligible candidates. Hence, we have covered the top commonly asked Python interview questions to familiarize you with the knowledge and skills required to succeed in your next Python job interview.

Going through these Python programming interview questions will help you to land your dream job in Data Science, Machine Learning or just Python coding. These Python basic interview questions will surely boost your confidence to face an interview and will definitely prepare you to answer the toughest of questions in the best way possible. These Python developer interview questions are suggested by experts and have proven to have great value.


Read More