Jan 5, 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: , Color: Red
Index: , Color: Green
Index: , 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
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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.6977613,"math_prob":0.7760968,"size":3457,"snap":"2022-40-2023-06","text_gpt3_token_len":885,"char_repetition_ratio":0.10338836,"word_repetition_ratio":0.011516315,"special_character_ratio":0.29013595,"punctuation_ratio":0.19908814,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9727757,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-04T18:08:27Z\",\"WARC-Record-ID\":\"<urn:uuid:bbc6b215-32fd-4065-981f-68345ce9df98>\",\"Content-Length\":\"27015\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7b958115-84f5-4096-a831-1dcfdd12f871>\",\"WARC-Concurrent-To\":\"<urn:uuid:b3c4188d-0d23-40b9-87df-d724f0d5f681>\",\"WARC-IP-Address\":\"45.55.52.176\",\"WARC-Target-URI\":\"https://techbrij.com/python-interview-questions\",\"WARC-Payload-Digest\":\"sha1:NAS7DJGB4FDNVOF54PM5HPKWSNZQNQBV\",\"WARC-Block-Digest\":\"sha1:UNUHEFQUCB4DEB7OGDHDAZKGLCTJR4UQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500151.93_warc_CC-MAIN-20230204173912-20230204203912-00229.warc.gz\"}"}