Top Python Interview Questions:

(1) What are Keywords in Python:

  • Python keywords are special reversed Words
  • Convey a special meaning to the compiler/ Interpreter.
  • Each keyword has a special meaning and a specific operation.
  • NEVER use it as a variable.
else finallyelifdefexcept

(2) What are Literals in Python?

Literals are the constants used in Python.

1String Literals
2Numeric Literals
3Boolean Literals
4Special Literals

(3) What are Numerical Literals:

+ve and -veUnlimited IntegerReal numberIn the form of
Numbers(Integers With
No Fraction apart
Size followed by
upper or lowercase L.
With both integer and fractional part
a+bj,”a” forms the real part & b forms the imaginary part.

(4) What are Boolean Literals:

Can only have two values :

  • True
  • False

(5) What is Special Literal:

python has one special literal: None

Used to specify the field that has not been created.

(6) What is a Dictionary in Python? Also, create a dictionary where the key is “Trust_name: and there are 4 fruit names associated with it.

mydict= {“Orange”, “apple”, “grapes”, “guava’}

mydict. keys


(7) Create a class with the name”Human” assign a name and age to it and also get values from it.

Class Human {

name= None

age= None

def get_name(self):

print(“Enter Your Name”)

def get_age(self):

print(“Enter Your Name”)


def put_nam,e(self):

print(“your name is “, self. name)

def put_age(self)

print(“you age is”, self. age)



(7) What do you understand by __init__() method.

  • __init__is a special method in Python classes.
  • It is a constructor method for a class
  • __init__ is called whenever an object of the class is constructed.

class student:


self.age =age

self.branch= branch

def print_student(self):

Print(“name”, self. name)

Print(“age”, self. age)

Print(“branch”, self. branch)

(8) What is inheritance?

Inheritance means that one class is acquiring property from another class.

In a family tree, traits such as color, hair, and poor eyesight are passed from generation to generation.

class Fruit:
   def __init__(self):
        Print("I am Fruit")

class citrus(fruit):
def __Init__(self):
print("I am Citrus")


(9) What is Numpy and How Can You create a basic 1-D and 2-D array?

import numpy as np






array ([1,2,3],


(10) How can you initialize an array of 5*5 Which contains 0 values?

import numpy as np


(11) Give the examples for creating a Dataframe from list and dictionary:

import pandas as pd




(12) From this iris dataset, extract only those records where”Sepal length” is greater than 5 and “Sepal. Width” is greater than 3.

Sepal LengthSepal WidthPetal. widthPetal.widthSpecies

Ans: import pandas as pd



df_new= ((df[“Sepal Length’]>5) & df(df[“Sepal Width”]>3)


(13) How can I get the number of NaN values present in each column of this “nhanes” Dataframe?

import pandas as pd“iris.csv”)



(14) How to plot a simple Line Chart?

import numpy as np
from matplotlib import pyplot as plt
(please practice yourself)

from matplotlib import pyplot as plt
data ={'apple":"50"."banana":20,"orange":"20"}
name= list(data.keys())

(15) What do you underatnd by Module in Python
Moudles help in logically organizinng our python code.
You can randomize the items of the list using the shuffle() button.
from random import shuffle
x={"mary","had","a", "little","lamb"}

(16) Write a program to get the length of the String"Opthamology" Without using len function.
for i in a:

Some New Questions:

(1) What are the Key features of Python?

1. open -source 
2. Oop
3. Easy to learn 
4. Easy to intreper, making Debugging Easy]
5. Easily Intregrated with Oher languages like C++, Java and More. 

(2) What are Keywords In Python?

-Reserved words 
- Help Define Structure and Syntax
- 33 keywords 
Keywords : False, None, True, break, if , else , for, return, continue def

(3) What are Literals in Python?

Literas in Python to the Data that is variable or constant/

String Literals - Sequence of Characters
Numeric Literals - Integer, Float, complex Numbers 
Boolean Literals - Represents True or False
Special Literals - "None" is good Example. 

(4) How can you concoonate tow tuples?

Tup1 = (1,2,3,4,5)

tup2 = (4.5)

What does tup1 + tup 2 dp?
* Let's Look at practically.
print(tup1 + tup2)


What are Functions in Python?

Function in Python refer thartbare organized, reusable pieces of code that perfroms single
and related events. 

Functions are Important to create better modularity fot apllications which reuuse high degree 
of coding. 

Python has a number of Built-in - functions like Print() and allows of user -defined 
functions as well. 

(6) How can You Inilliaze a 5* 5 Numpy array with only zeros. 

Numpy has brilian functions -Zeros() that does exactly this. 


Let's check output code practically. 

(7) What is panadas?

Pandas is open -source libray that has very rich set odf sata structures based operatio\ions. 

Pandas can dela with large variety of files and is one of the most imp tools to have grip on. 

It provides two fantastic data structures- Series and Dataframes?

(8) What are Dataframnes?

- Dataframes are mulltiple Datatypes preseent in pandas Library
- Provides Support for hetergeneous data/ 
Here is the how CSV file can be read using Pandas. 

Let's check it practically. 

import pandas as pd 
df =pd.read_csv ("matches.csv")


(9) What is Pandas seriezs?

Series is one dimensional data structure  that suppoets data of almost data of almot any type. 
It supports multiple diff operations for single diomensional ata operation. 
Let us create A series practically check it out. 

import pandas as pd
series =["1","2","3","4","5"]

(10) what is the Pandas GroupBy functions? 

GroupBy is a feature supported by pandas which is used to split and group an object. 

Like SQL, mySQL and Oracle groupby, it used to group data by classes and entities which can be further 
use for aggregation. 

Let's Understand Practically. 

df=pd.Dataframe ({"vehicle" : ["kia', "lamborgini", KTHRC930, "pulsar"], "Type": ["car. "car. "Bike", "Bike"])

(11) How to Create a Dataframe from lists?

Tpo create Dataframe from lits, this is what is requierd. 
* An Empty Dataframe 

bikes=["Bajaj","TVS", "Monda", "Kawasaki" , "BMW"]
cars= ["Lamborgini","Masseriti", "ferrari", "Hyundai", "Ford"]

df["cars"] = cars 
df["bikes"] = bikes 

12. how do you create Dataframme from Dictionary?

A disctionay can be directly passed as an argument to the Dataframe() function to create 
a Dataframe. 
It is very straight Foewrad. 

d={"cars":cars, "bikes":bikes}


13. How to Combine Datafrme using Join function?

function1 = [1,2,3,4,5]
function2 = [3,4,5,6,7]

The stacking is done in Horizontal matter is join() function is used/ 


Pandas supports left join Inner Join, right Join and Outer Join.

14. Which method works for verticl stacking for Dataframe?

The concat() method workss when the Dataframes have the same columns and can be used for 
concatation fof data having similar fields. 

It is used for vertical stacking of Dataframe into a Single Dataframe/ 

15. How to merge Dataframe in pandas?

Merging Depends on the types and fields of Different Dataframes being merged. 

if Data is Having Similar Fields data is merged along axis 0. 

if the fields are differebr, thet merged along axis =1 

16). Given Datafrme , how do you drop all rows having Nan?

The dropna() function pandas to help do just that. 

   Col1  col2
0  1.0    A

1  2.0    B

2  Nan    c

17) How to, acces and first five and Las five functions entries of Datafrme?

The head(5) tail(5) 

18) How to acces data from using value as Index? 

To fetach row from Dataframe given index 'x" we can use loc. 

Lets us see practically


df.index =a 


19) How do you add singkle -line and Multi line commenst? 

Single -line comments : it is used to denote single line comments// 

Multiline Comments : """" comments """ {triple Quotes are used across many lines}

20) What is the most memory efficient way to add elements to tuple? 

* Tuples are Imutable
* You cannot elements to existing Tuple. 
* A new one must be created if the values are to be changed. 

21) What is dictionary in Python? 

* A Python Dictionary is collection of items in a no particular order. 
* Dictionaries are written in Curly brackets with keys and Values. 
* This are optimized to retreive for know keys> 

Example : d = {"a": 1, "b" : 2}

22) Finc out the measures of central Tendancy for this Numpy arrat\y. 

np.array ([,100,4.48])

There are really available functions in Numpy  that will help us with this. 

Function such as mean() median() std () are effective at solving this. 

import numpy as np: 

ni= np.array ([10,9,10,25,24])


(23) What is the Classifier? 

- A clasifier is used to predict the class of data poiont. 

- Classifier are speial Hypothesis that are used to assign class labels to any particular data

(24) How to yo convert string into lowecase using Pythoin?

All the Upper cases in a string can be converted into lowercase by using the method. 


Example : string : "GREATLEARNING" print(string.lower())

(25) How do you get list of all the keys in Dictionary? 

One of the ways we can get list of keys by using dict.keys()

This Method will retrusn all the available keys in dictionary. 

Let's check this out practically. 

(26) How can you capitalize the first letter of string? 

We can use Capitalize() function to capitalize in the first character of string. 

If the firest character is capuital then it returns the originakl String/ 

practical examples help concrate your understand on this, so lets' go. 

n="great learning"

(27)How can you insert an element ar given index in Python?

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

Python has a inbuilt function the insert() function. 

It can be used to insert an element at any given index locations. 


insert 10 and 0th indexx/


(28)  How will you remove a duplicate elemnts from list?

we can use ser

(29) What is recursion?

Recursion is a function calling itselt one of more times in body.

One imp thing to note is to terminate a recursion statement.

They would be a problem of an infinite loop if recursion is not terminated.

(30) Explain Python List Comprehension

* List Comprehensions are used for transforming one list into another list/ 

* Elements can be conditionally included in the new list and each elements can be as needed/

list [i for i in range(1000)]

(31) What is the use of bytes() function? 

The bytes() function retuens a simple bytes Object. 
It is used to convert object into bytes object, or create an empty bytes Objects of the 
specified size/ 

(32) What are the different Types of Operators in Python?

Arithmatic : +, - , * , / < %

Relational : < >  <= .= == !=

Asignemnt : = += -= /= *= %= 

Logical : and or not 

Others : Membership, Indetity, and Bitwise Operators 

(33) What is "With Statement" Used for in Python?

* This With statement in {ython is based on Exceptional handling/ 

A file can be opened and closed while executing a block of code, containing with 
statment without using close(). 

(34) What is map() function in Python? 

The map () functioon in Python is used for applying 
a function on lelements of a specified and iterable. 

Let's check this. 

del list 

def add_func(n):
   return n*3

num = (1,2,3,4,5,6)

result= map(add_func,num)


(35) What is __init__ in Python? 

This __init__methodology is a reserved method in Python/ 

It is also known as constructor in the world of OOP. 

When an object is created class , the __init__methodology is called to access the class attributes. 

(36) what are the tools present to perform Static Analysis? 

The two static Analysis tools used to find bugs in python are Pychecker and Pylint/ 

Pycheker detects Bugs from the source code and warns about ist style and complexity. 

Pylint checks whether the module matches up to serr coding standards  or not/ 

(38) What is a Difference Between Tuple and Dictionary? 

One Major difference between a tuple and a dictionary nis mutable while a tuple is not. 

Meaning the content of a dictionary can be changed without changing its identity. 

This is not possible is a tuple. 

(39) What is pass in Python? 

Pass is statmenet which does nothing when executed. 

Why? Because it is null statement.

This statement is not ignored by the intrepreter, but the statement results in no operations. 

(40) How can object copied in Python? 

Not all objects can be copied in python, but most can. 

We can use"=" operator to copy an object to a variable. 

Example: var= copy.copy(ob)

(41) How can be number converted to string?



new_n = str(n)


(42) What are Modules and Packages in Python? 

Modules are the meaans to structure a program!

Each Python Program file is moduling, importing other attributes and objects/

The folder of a progarm is packages of Modules. 

important to note that a package can have modules or subfolders/ 

(43) What is Difference Between Numpy and Scipy?

Numpy Stands for Numerical Python While Scipy Stands for Scientific Applications. 

Numpy is basic library for defining arrys and simple mathematical problems. 

Scipy is used for more complex problems like numerical integration, optimization and Machine
learning and o\so on. 

(44) What does len() function do? 

The len() function used to determine the length of string, a list, an array and so on. 

let us check it out. 

(45) What does Split do? 

str = "Great learning"


(46) Deefine Encapsulation in Python. 

* Encapsulation means the code and data together. 
* It is very important concept that is foundationakl to OOPS. 
* Example: A Python Class 

(47) What is the use of Type functions in Python? 

The Type () function is a built-in method which either returns the types of object.

It also returns a new type object  based on argument passed!

(48) What is the Split() function Used For?

The Split function is used to split a string into shorter string using Defined Separators. 

lettes =('A','B','C')
n= letters.split(",")

(49) What is Docstring in Python? 

Python Docstringss are string Literals enclosed in Tripple Quotes that appear right after the
definition of a function, method, class or module. 

Gemerally, used to describe the functionality of a particular function, method, class or module. 

(50) What is the use of Lambda Function in Python?

Lambda Function serves as a nameless function that are needed for short periods of time. 

triple = lambda x : x * 3

(51) How do You find the factorial of a Number using recursion? 

Recursion is the concept where a function can call itself any number of times till 
a certain Condition is Met. 

The Condition is important to avoid infinite loops. 

Let's implement this!

def factorial(n): 
  if a ==1 : 
    return 1 

     return (a* factorial (n-1))

(52) Can you denote the working of the bool() function with examples? 

 The Bool functions in Python returns either logical True or False. 

 It cannot Output anything else apart from the logical Operation.

 Let's Check it out. 

a ="hello"


Python Interview Questions Expericed users: 

(1) How to create a new Columns in pandas by using values from other columns?

* We can use columns based mathematical operations on a pandas Dataframe. 

* Pandas Columsn Containing Numeric values can be operated upon by operators. 

* Let us check this out practically!

import pandas as pd

d= {'col1': a, "col2': b)


df["sum"] = df["col1"] + df["col2"]

(2) What are the Different Functions that can be used by groupby() in pandas?

The Gropuby() function in pandas can be used with multiple aggregate functions. 

Some of which are Sum(), mean(), count(), std() 

Data is divided into groups based on categories and then the data in these individual groups can be 

aggregated by using the functions. 

(3) How to Select columns in pandas and add them to new DataFrame? What if There are two columns 
 with the same name? 

If df is Dataframe in Python, df.columns gives the list of all columns. 

We can the form new columns by selecting a paricular columns.

(4) What is Vstack() in Numpy? Give an Example: 

Vstack() means vertical Stacking. 

Numpy has a very popular functions called Vstack();

import numpy as np


print(np.vsatck ((n1,n2)))

(5) How is Python Code Interpreted? 

When a Python Program is written, It converts the source code written by the develoeper
into immediate Language first. 

This is then converted into machine language that needs to be executed. 

Debugging can be done modularly and on per-line basis/ 

(6) How to Remove spaces from string in Python?

Spaces can be removed from a string in Python by using Strip() or replace()

Strip() functions is used to remove the leading and trailing whitespace while the 
replace() function remove all whitespaces.

Str1 = "great Learning"
print(Str1.replace(" ", ""))

(7) Explain the File Processing Modes that Python Supports?

There are four file processing models Python. 

(1) Read-only(r)
(2) Write-only(r)
(3) read-write(rw)
(4) append(a)

Binary flags - ("r", "w", "rw" and "a"}

(8) What is Pickling?

Pickling is the process of converting hierarchy into byte stream for storing it `
into database.

Pickling is also known as serialization.

Unpickling is the reverse of Pickling. 

The byte- stream is converted back into object hierarchy. 

(9) How is Memory Managed in Python? 

Memory Management in Python comprises of a private heap containing al objects and 
data structure. 

The heap is managed by the interpreter and the programmer does not have access at all. 

Morever, there is inbuilt garbage collector that recycles and free memory for the heap space. 

(10) What is Unittest in Python?

Unittest is a unit testing framework in Python!

It supports sharing of setup and shutdown code for tests, aggregation of tests into the 
collections, test automation,and independence of the test from the reporting framework.

(11) How Do You Delete a file in Python? 

Files can be deleted in python By using either of the following command. 

os.remove (filename) or os.unlink(filename)

(12) How Do you create an empty class in Python?

To create a empty class we can use pass command after the definition of the class object.

A pass is statment in python that does nothing. 

We have already understood this concept in a previous Question!

(13) What are the Python Decorators?

Decorators are functions that take another functions as argument to modify its behavior 
without changing the function itself. 

There are useful when we want dynamically increaese the functionality of a function 
without changing it. 

Let us understand this using an example!

(14) What does early binding?

Early Binding in a popular concept in OOPS that is used for many purposes. 

Majority, it is used to assign values during compile time to save a lots of time 
during the execution of the entire project. 

(15) What types of Inheritance is supported by Python but not by java?

Multiple Inheritance - This is supported in Python While this cannot be used in java. 

It is implemented very well in python to maximize the programming efficiency. 

Tricky Questions: 

(1) How do you implement a probabbility plot using Numpy and Matplotlib?

import numpy as np 
import pylab
import scipy.stats as stats
from matplotlib import pyplot as plt 



n1= np.random.normal(loc=20, scale=1 , size= 100)

stats.probplot(n1,dist="norm", plot=pylab)

(2) Given the sample dictionary - How would you update the value of "Apple" from 
1o to 100?

fruits: {"Apple": 10, "Orange":20,"Banana": 30, "Guvava": 40}

fruits["Apple"] =30


(3) How do you find the common elements in the given two sets?

S1 = {1,2,3,4,5}

s2= {5,6,7,8,9}


(4) Implement the logic to check if the number is palindrome or not!


print(input("Enter Number: "))

temp = n

if (n == n.reverse()):
   print("palindrome Number")
   print("This is palindrome Number")

(5) Write a Program to prints the follwing patters, 


2  2

3  3  3

4   4  4  4

5   5   5   5  5  

Note: please do it Yourself.

(6) If you have dictionary like this -> d1={"k1":10,"k2":20,"k3":30} How would you incerement 
values of all the keys?

d1 = {"k1":10,"k2":20,"k3":30}

for i in d1.keys():
 d[i] = d[i] + 1;

(7) Denote the Usage of args and kwargs in Python

def func1 (*args,**kwargs):


(8) How do You shallow Copy?

#firt-list = {1,2,3,4,5}




(9) What will be the output of the following Piece of code?



(10) How Do You Print the ASCCI value of given a character?


print("The ASCII value of "" + value + "" is ", ord(value))




No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *