Python Interview Questions Set - 6 Released
Intermediate Level
Is Python case sensitive when dealing with identifiers?
Yes. Python is case-sensitive when dealing with identifiers. It is a case
sensitive language. Thus, variable and Variable would not be the same.
How to create a new column in pandas by using values from other
columns?
We can perform column based mathematical operations on a pandas
dataframe. Pandas columns containing numeric values can be operated
upon by operators.
Code:
import pandas as pd
a=[1,2,3]
b=[2,3,5]
d={"col1":a,"col2":b}
df=pd.DataFrame(d)
df["Sum"]=df["col1"]+df["col2"]
df["Difference"]=df["col1"]-df["col2"]
df
What are the different functions that can be used by grouby in
pandas ?
grouby() 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 the aforementioned
functions.
How to delete a column or group of columns in pandas? Given the
below dataframe drop column “col1”.
drop() function can be used to delete the columns from a dataframe.
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df=df.drop(["col1"],axis=1)
df
Output
Given the following data frame drop rows having column values
as A.
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df.dropna(inplace=True)
df=df[df.col1!=1]
df
Output:
col1 2, 3
col2 B, C
What is Reindexing in pandas?
Reindexing is the process of re-assigning the index of a pandas
dataframe.
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
Output:
What do you understand about the lambda function? Create a
lambda function which will print the sum of all the elements in
this list -> [5, 8, 10, 20, 50, 100]
Lambda functions are anonymous functions in Python. They are
defined using the keyword lambda. Lambda functions can take any
number of arguments, but they can only have one expression.
from functools import reduce
sequences = [5, 8, 10, 20, 50, 100]
sum = reduce (lambda x, y: x+y, sequences)
print(sum)
What is vstack() in numpy? Give an example.
vstack() is a function to align rows vertically. All rows must have the
same number of elements.
Code:
import numpy as np
n1=np.array([10,20,30,40,50])
n2=np.array([50,60,70,80,90])
print(np.vstack((n1,n2)))
Output
[[10 20 30 40 50], [50 60 70 80 90]]
Explain the file processing modes that Python supports.
There are three file processing modes in Python: read-only(r), write
only(w), read-write(rw) and append (a). So, if you are opening a text
file in say, read mode. The preceding modes become “rt” for read-only,
“wt” for write and so on. Similarly, a binary file can be opened by
specifying “b” along with the file accessing flags (“r”, “w”, “rw” and “a”)
preceding it.
What is pickling and unpickling?
Pickling is the process of converting a Python object hierarchy into a
byte stream for storing it into a database. It is also known as
serialization. Unpickling is the reverse of pickling. The byte stream is
converted back into an object hierarchy.
How is memory managed in Python?
This is one of the most commonly asked python interview questions
Memory management in python comprises a private heap containing
all objects and data structure. The heap is managed by the interpreter
and the programmer does not have access to it at all. The Python
memory manager does all the memory allocation. Moreover, there is an
inbuilt garbage collector that recycles and frees memory for the heap
space.
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
collections,test automation, and independence of the tests from the
reporting framework.
How do you delete a file in Python?
Files can be deleted in Python by using the command os.remove
(filename) or os.unlink(filename)
How do you create an empty class in Python?
To create an empty class we can use the pass command after the
definition of the class object. A pass is a statement in Python that does
nothing.
What are Python decorators?
Decorators are functions that take another function as an argument to
modify its behavior without changing the function itself. These are
useful when we want to dynamically increase the functionality of a
function without changing it.
Here is an example:
def smart_divide(func):
def inner(a, b):
print("Dividing", a, "by", b)
if b == 0:
print("Make sure Denominator is not zero")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
divide(1,0)
Here smart_divide is a decorator function that is used to add
functionality to simple divide function.
What is a dynamically typed language?
Type checking is an important part of any programming language
which is about ensuring minimum type errors. The type defined for
variables are checked either at compile-time or run-time. When the
type-check is done at compile time then it is called static typed
language and when the type check is done at run time, it’s called
dynamically typed language.
1. In dynamic typed language the objects are bound with type by
assignments at run time.
2. Dynamically typed programming languages produce less
optimized code comparatively
3. In dynamically typed languages, types for variables need not be
defined before using them. Hence, it can be allocated
dynamically.
What is the difference between Python Arrays and lists?
Python Arrays and List both are ordered collections of elements and
are mutable, but the difference lies in working with them
Arrays store heterogeneous data when imported from the array
module, but arrays can store homogeneous data imported from the
numpy module. But lists can store heterogeneous data, and to use lists,
it doesn’t have to be imported from any module.
import array as a1
array1 = a1.array('i', [1 , 2 ,5] )
print (array1)
Output:
array('i', [1,2,5])
or
import numpy as a2
array2 = a2.array([5, 6, 9, 2])
print(array2)
Output
[5 6 9 2]
1. Arrays have to be declared before using it but lists need not be
declared.
2. Numerical operations are easier to do on arrays as compared to
lists.
What is Scope Resolution in Python?
The variable’s accessibility is defined in python according to the
location of the variable declaration, called the scope of variables in
python. Scope Resolution refers to the order in which these variables
are looked for a name to variable matching. Following is the scope
defined in python for variable declaration.
a. Local scope – The variable declared inside a loop, the function body
is accessible only within that function or loop.
b. Global scope – The variable is declared outside any other code at the
topmost level and is accessible everywhere.
c. Enclosing scope – The variable is declared inside an enclosing
function, accessible only within that enclosing function.
d. Built-in Scope – The variable declared inside the inbuilt functions of
various modules of python has the built-in scope and is accessible only
within that particular module.
The scope resolution for any variable is made in java in a particular
order, and that order is
Local Scope -> enclosing scope -> global scope -> built-in scope
What are Dict and List comprehensions?
List comprehensions provide a more compact and elegant way to
create lists than for-loops, and also a new list can be created from
existing lists.
The syntax used is as follows:
1 a for a in iterator
Or,
1 a for a in iterator if condition
Ex:
list1 = [a for a in range(5)]
print(list1)
Output: [0 1 2 3 4]
list2 = [a for a in range(5) if a < 3]
print(list2)
Output: [0 1 2]
Dictionary comprehensions provide a more compact and elegant way to
create a dictionary, and also, a new dictionary can be created from
existing dictionaries.
The syntax used is:
1 {key: expression for an item in iterator}
Ex:
dict([(i, i*2) for i in range(5)])
Output: {0:0, 1:2, 2:4, 3:6, 4:8}
What is the difference between xrange and range in Python?
range() and xrange() are inbuilt functions in python used to generate
integer numbers in the specified range. The difference between the two
can be understood if python version 2.0 is used because the python
version 3.0 xrange() function is re-implemented as the range() function
itself.
With respect to python 2.0, the difference between range and xrange
function is as follows:
1. range() takes more memory comparatively
2. xrange(), execution speed is faster comparatively
3. range () returns a list of integers and xrange() returns a
generator object.
Example:
for i in range(1,10,2):
print(i)
Output: 1 3 5 7 9
What is the difference between .py and .pyc files?
.py are the source code files in python that the python interpreter
interprets.
.pyc are the compiled files that are bytecodes generated by the python
compiler, but .pyc files are only created for inbuilt modules/files.
Recent Comments
Archives
Categories
Categories
- Inspiration (1)
- Style (1)
- Technical Blog (30)
- Tips & tricks (2)
- Uncategorized (25)