What are the key features of Python?
Python is one of the most popular programming languages used by data scientists and AIML professionals. This popularity is due to the following key features of Python:
- Python is easy to learn due to its clear syntax and readability
- Python is easy to interpret, making debugging easy
- Python is free and Open-source
- It can be used across different languages
- It is an object-oriented language which supports concepts of classes
- It can be easily integrated with other languages like C++, Java and more
What are Keywords in Python?
Keywords in Python are reserved words which are used as identifiers, function name or variable name. They help define the structure and syntax of the language.
There are a total of 33 keywords in Python 3.7 which can change in the next version, i.e., Python 3.8. A list of all the keywords is provided below:
Keywords in Python
False | class | finally | is | return |
None | continue | for | lambda | try |
True | def | from | nonlocal | while |
and | del | global | not | with |
as | elif | if | or | yield |
assert | else | import | pass | |
break | except |
What are Literals in Python and explain about different Literals?
Literals in Python refer to the data that is given in a variable or constant. Python has various kinds of literals including:
- String Literals: It is a sequence of characters enclosed in codes. There can be single, double and triple strings based on the number of quotes used. Character literals are single characters surrounded by single or double-quotes.
- Numeric Literals: These are unchangeable kind and belong to three different types – integer, float and complex.
- Boolean Literals: They can have either of the two values- True or False which represents ‘1’ and ‘0’ respectively.
- Special Literals: Special literals are sued to classify fields that are not created. It is represented by the value ‘none’.
Python Interview Question
How can you concatenate two tuples?
Solution ->
Let’s say we have two tuples like this ->
tup1 = (1,”a”,True)
tup2 = (4,5,6)
Concatenation of tuples means that we are adding the elements of one tuple at the end of another tuple.
Now, let’s go ahead and concatenate tuple2 with tuple1:
Code
tup1=(1,"a",True)
tup2=(4,5,6)
tup1+tup2
Output

All you have to do is, use the ‘+’ operator between the two tuples and you’ll get the concatenated result.
Similarly, let’s concatenate tuple1 with tuple2:
Code
tup1=(1,"a",True)
tup2=(4,5,6)
tup2+tup1
What are functions in Python?
Functions in Python refer to blocks that have organized and reusable codes to perform single, and related events. Functions are important to create better modularity for applications which reuse high degree of coding. Python has a number of built-in functions like print(). However, it also allows you to create user-defined functions.
How to Install Python?
To Install Python, first go to Anaconda.org and click on “Download Anaconda”. Here, you can download the latest version of Python. After Python is installed, it is a pretty straightforward process. The next step is to power up an IDE and start coding in Python.
Advance Python Interview Question
What is Python Used For?
Python is one of the most popular programming languages in the world today. Whether you’re browsing through Google, scrolling through Instagram, watching videos on YouTube, or listening to music on Spotify, all of these applications make use of Python for their key programming requirements. Python is used across various platforms, applications, and services such as web development.
How can you initialize a 5*5 numpy array with only zeroes?
Solution ->
We will be using the .zeros() method
import numpy as np
n1=np.zeros((5,5))
n1
Use np.zeros() and pass in the dimensions inside it. Since, we want a 5*5 matrix, we will pass (5,5) inside the .zeros() method.
This will be the output:

What is Pandas?
Pandas is an open source python library which has a very rich set of data structures for data based operations. Pandas with it’s cool features fits in every role of data operation, whether it be academics or solving complex business problems. Pandas can deal with a large variety of files and is one of the most important tools to have a grip on.
Python Interview Question
What are data frames?
A pandas data frame is a data structure in pandas which is mutable. Pandas has support for heterogeneous data which is arranged across two axes.( rows and columns).
Reading files into pandas:-
Import pandas as pd
df=p.read_csv(“mydata.csv”)
Here df is a pandas data frame. read_csv() is used to read a comma delimited file as a data frame in pandas.
What is a Pandas Series?
Series is a one dimensional pandas data structure which can data of almost any type. It resembles an excel column. It supports multiple operations and is used for single dimensional data operations.
Creating a series from data:
Code
import pandas as pd
data=["1",2,"three",4.0]
series=pd.Series(data)
print(series)
print(type(series))
Output

What is pandas group by?
A pandas group by is a feature supported by pandas which is used to split and group an object. Like the sql/MySQL/oracle group by it used to group data by classes, entities which can be further used for aggregation. A data frame can be grouped by one or more columns.
Code
df = pd.DataFrame({'Vehicle':['Etios','Lamborghini','Apache200','Pulsar200'], 'Type':["car","car","motorcycle","motorcycle"]})
df
Output

To perform group by type the following code:
df.groupby('Type').count()
Output

How to create a data frame from lists?
To create a data frame from lists ,
1)create an empty data frame
2)add lists as individuals columns to the list
Code
df=pd.DataFrame()
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
df["cars"]=cars
df["bikes"]=bikes
df
Output

Advance Python Interview Question
How to create data frame from a dictionary?
A dictionary can be directly passed as an argument to the DataFrame() function to create the data frame.
Code
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
df
Output

How to combine data frames in pandas?
Two different data frames can be stacked either horizontally or vertically by the concat(), append() and join() functions in pandas.
Concat works best when the data frames have the same columns and can be used for concatenation of data having similar fields and is basically vertical stacking of data frames into a single data frame.
Append() is used for horizontal stacking of data frames. If two tables(data frames) are to be merged together then this is the best concatenation function.
Join is used when we need to extract data from different data frames which are having one or more common columns. The stacking is horizontal in this case.
Before going through the questions, here’s a quick video to help you refresh your memory on Python.
What kind of joins does pandas offer?
Pandas has a left join, inner join, right join and an outer join.
Python Interview Question
How to merge data frames in pandas?
Merging depends on the type and fields of different data frames being merged. If data is having similar fields data is merged along axis 0 else they are merged along axis 1.
Give the below data frame drop all rows having Nan.
The dropna function can be used to do that.
df.dropna(inplace=True)
df
How to access the first five entries of a data frame?
By using the head(5) function we can get the top five entries of a data frame. By default df.head() returns the top 5 rows. To get the top n rows df.head(n) will be used.
Advance Python Interview Question
How to access the last five entries of a data frame?
By using tail(5) function we can get the top five entries of a data frame. By default df.tail() returns the top 5 rows. To get the last n rows df.tail(n) will be used.
How to fetch a data entry from a pandas data frame using a given value in index?
To fetch a row from data frame given index x, we can use loc.
Df.loc[10] where 10 is the value of the index.
Code
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df.loc[10]
Output

What are comments and how can you add comments in Python?
Comments in Python refer to a piece of text intended for information. It is especially relevant when more than one person works on a set of codes. It can be used to analyze code, leave feedback, and debug it. There are two types of comments which includes:
- Single-line comment
- Multiple-line comment
Codes needed for adding comment
#Note –single line comment
“””Note
Note
Note”””—–multiline comment
Python Interview Question
What is the difference between list and tuples in Python?
Lists are mutable, but tuples are immutable.
What is dictionary in Python? Give an example.
A Python dictionary is a collection of items in no particular order. Python dictionaries are written in curly brackets with keys and values. Dictionaries are optimized to retrieve value for known keys.
Example
d={“a”:1,”b”:2}
Find out the mean, median and standard deviation of this numpy array -> np.array([1,5,3,100,4,48])
import numpy as np
n1=np.array([10,20,30,40,50,60])
print(np.mean(n1))
print(np.median(n1))
print(np.std(n1))
Advance Python Interview Question
What is a classifier?
A classifier is used to predict the class of any data point. Classifiers are special hypotheses that are used to assign class labels to any particular data points. A classifier often uses training data to understand the relation between input variables and the class. Classification is a method used in supervised learning in Machine Learning.
In Python how do you convert a string into lowercase?
All the upper cases in a string can be converted into lowercase by using the method: string.lower()
ex: string = ‘GREATLEARNING’ print(string.lower())
o/p: greatlearning
How do you get a list of all the keys in a dictionary?
One of the ways we can get a list of keys is by using: dict.keys()
This method returns all the available keys in the dictionary. dict = {1:a, 2:b, 3:c} dict.keys()
o/p: [1, 2, 3]
Python Interview Question
How can you capitalize the first letter of a string?
We can use the capitalize() function to capitalize the first character of a string. If the first character is already in capital then it returns the original string.
Syntax: string_name.capitalize() ex: n = “great learning” print(n.capitalize())
o/p: Great learning
How can you insert an element at a given index in Python?
Python has an inbuilt function called the insert() function.
It can be used used to insert an element at a given index.
Syntax: list_name.insert(index, element)
ex: list = [ 0,1, 2, 3, 4, 5, 6, 7 ]
#insert 10 at 6th index
list.insert(6, 10)
o/p: [0,1,2,3,4,5,10,6,7]
How will you remove duplicate elements from a list?
There are various methods to remove duplicate elements from a list. But, the most common one is, converting the list into a set by using the set() function and using the list() function to convert it back to a list, if required. ex: list0 = [2, 6, 4, 7, 4, 6, 7, 2]
list1 = list(set(list0)) print (“The list without duplicates : ” + str(list1)) o/p: The list without duplicates : [2, 4, 6, 7]
Advance Python Interview Question
What is recursion?
Recursion is a function calling itself one or more times in it body. One very important condition a recursive function should have to be used in a program is, it should terminate, else there would be a problem of an infinite loop.
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 element can be transformed as needed. It consists of an expression leading a for clause, enclosed in brackets. for ex: list = [i for i in range(1000)]
print list
What is the bytes() function?
The bytes() function returns a bytes object. It is used to convert objects into bytes objects, or create empty bytes object of the specified size.
Python Interview Question
What are the different types of operators in Python?
Python has the following basic operators:
Arithmetic( Addition(+), Substraction(-), Multiplication(*), Division(/), Modulus(%) ), Relational ( <, >, <=, >=, ==, !=, ),
Assignment ( =. +=, -=, /=, *=, %= ),
Logical ( and, or not ), Membership, Identity, and Bitwise Operators
What is the ‘with statement’?
“with” statement in python is used in exception handling. A file can be opened and closed while executing a block of code, containing the “with” statement., without using the close() function. It essentially makes the code much more easy to read.
What is a map() function in Python?
The map() function in Python is used for applying a function on all elements of a specified iterable. It consists of two parameters, function and iterable. The function is taken as an argument and then applied to all the elements of an iterable(passed as the second argument). An object list is returned as a result.
def add(n):
return n + n number= (15, 25, 35, 45)
res= map(add, num)
print(list(res))
o/p: 30,50,70,90
Advance Python Interview Question
What is __init__ in Python?
_init_ methodology is a reserved method in Python aka constructor in OOP. When an object is created from a class and _init_ methodolgy is called to access the class attributes.
What are the tools present to perform statics analysis?
The two static analysis tool used to find bugs in Python are: Pychecker and Pylint. Pychecker detects bugs from the source code and warns about its style and complexity. While, Pylint checks whether the module matches upto a coding standard.
What is the difference between tuple and dictionary?
One major difference between a tuple and a dictionary is that dictionary is mutable while a tuple is not. Meaning the content of a dictionary can be changed without changing it’s identity, but in tuple that’s not possible.
Python Interview Question
What is pass in Python?
Pass is a statement which does nothing when executed. In other words it is a Null statement. This statement is not ignored by the interpreter, but the statement results in no operation. It is used when you do not want any command to execute but a statement is required.
How can an object be copied in Python?
Not all objects can be copied in Python, but most can. We ca use the “=” operator to copy an obect to a variable.
ex: var=copy.copy(obj)
How can a number be converted to a string?
The inbuilt function str() can be used to convert a number to a string.
Advance Python Interview Question
What are module and package in Python?
Modules are the way to structure a program. Each Python program file is a module, importing other attributes and objects. The folder of a program is a package of modules. A package can have modules or subfolders.
What is object() function in Python?
In Python the object() function returns an empty object. New properties or methods cannot be added to this object.
What is the difference between NumPy and SciPy?
NumPy stands for Numerical Python while SciPy stands for Scientific Python. NumPy is the basic library for defining arrays and simple mathematica problems, while SciPy is used for more complex problems like numerical integration and optimization and machine learning and so on.
Python Interview Question
What does len() do?
len() is used to determine the length of a string, a list, an array, and so on. ex: str = “greatlearning”
print(len(str))
o/p: 13
Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class for example.
What is the type () in Python?
type() is a built-in method which either returns the type of the object or returns a new type object based on the arguments passed.
ex: a = 100
type(a)
o/p: int
Advance Python Interview Question
What is split() function used for?
Split fuction is used to split a string into shorter string using defined seperatos. letters = (” A, B, C”)
n = text.split(“,”)
print(n)
o/p: [‘A’, ‘B’, ‘C’ ]