Jan 05, 2020

Python Interview Questions

What is equivalent of "public static void main()" of Java in Python?


def main():
    # Code to execute

if __name__ == "__main__":
    main()

What is use of // and ** operators in Python?

// is a Floor Division operator used for dividing two operands with the result as quotient showing only digits before the decimal point. i.e. 7//5 = 1 and 7.0//5.0 = 1.0.

** is exponentiation operator i.e. 2**3 = 8 and 3**2 = 9

How do you get index in 'for...in' loop?

To keep track of the indices of list item, use enumerate() function:


list_colors = ['Red','Green','Blue']
for index, color in enumerate(list_colors): 
    print(f"Index: [{index}], Color: {color}")

Output:


Index: [0], Color: Red
Index: [1], Color: Green
Index: [2], Color: Blue

How do you merge two dictionaries in a single expression?


dict_a = {1: 'Ram', 2: "Krishna", 3:"Paramhansh"}
dict_b  = {2: 'Swami', 4: "Vivek"}

merged_dict = {**dict_a, **dict_b}
print(merged_dict)

Output:


{1: 'Ram', 2: 'Swami', 3: 'Paramhansh', 4: 'Vivek'}

What is Pickling and Unpickling?

Pickling: The process whereby a Python object hierarchy is converted into a byte stream.

Unpickling: Inverse operation of Pickling, whereby a byte stream is converted back into an object hierarchy.

Both are done using the pickle module.


import pickle
obj_orders = [{'product_id': '1233', 'amount': 108}, {'product_id': '1277', 'amount': 639 }]

# pickling
b_stream = pickle.dumps(obj_orders)   

# Unpickling
orders =  pickle.loads(b_stream) 
print(orders)

Output:


[{'product_id': '1233', 'amount': 108}, {'product_id': '1277', 'amount': 639}]

How do you write ternary operator without using if else keywords?

Using and and or conditions:

<condition> and <expression_on_true> or <expression_on_false>

Using tuple, dictionary or lambda expressions:

(<expression_on_false>,<expression_on_true>)[condition]

{True:<expression_on_true>, False: <expression_on_false>}[condition]

# using Lambda
result = (lambda: "Odd", lambda: "Even")[n % 2 == 0]()
print(result)

For more details with examples, read article: Python: Ternary Conditional Operator

How do you get unique values from a python list of objects?

Use a set comprehension. Sets are unordered collections of unique elements, means any duplicates will be removed.

Example:

Suppose class Order has product_id, qty, amount attributes. To get collection of unique product_id:


orders = [ ... ]
products = { order.product_id for order in orders}

If you want to transform a list into collection of unique elements, use set method.


a = ['a', 'b', 'c', 'd', 'b']
b = set(a)
print(b)

Output:


{'b', 'c', 'd', 'a'}

What is lambda function?

Lambda function is an anonymous function that can have any number of parameters but, can have just one statement.


exp = lambda x,y : x**y
print(exp(3,2))

Output: 9

What is use of __slots__?

By default, each python object has a __dict__ atttribute which is a dictionary containing all other attributes. You can imagine using a dictionary to store attribute takes some extra space & time for accessing it. But advantage is you can dynamically add attributes to objects of classes.

When you use __slots__, any object created for that class won't have a __dict__ attribute. Instead, all attribute access is done directly via pointers. It prevents the dynamic creation of attributes. So object instances has faster attribute access and space savings in memory.

If you are going to use thousands or millions of objects of the same class __slots__ is recommended for good performance.