More Python Interview Questions and Answers
11. Use lambda with map, filter, reduce
from functools import reduce
nums = [1, 2, 3, 4]
print(list(map(lambda x: x*2, nums))) # [2, 4, 6, 8]
print(list(filter(lambda x: x % 2 == 0, nums))) # [2, 4]
print(reduce(lambda x, y: x + y, nums)) # 10
12. Flatten a nested list
nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
print(flat) # [1, 2, 3, 4, 5]
13. Sort a dictionary by value
d = {'a': 3, 'b': 1, 'c': 2}
sorted_dict = dict(sorted([Link](), key=lambda x: x[1]))
print(sorted_dict) # {'b': 1, 'c': 2, 'a': 3}
14. Binary search implementation
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
15. Move all zeros to the end
def move_zeros(lst):
non_zeros = [x for x in lst if x != 0]
zeros = [0] * (len(lst) - len(non_zeros))
return non_zeros + zeros
print(move_zeros([0, 1, 0, 3, 12])) # [1, 3, 12, 0, 0]
16. Difference between 'is' and '=='
a = [1, 2, 3]
b = a
c = a[:]
print(a is b) # True (same object)
print(a == c) # True (same value)
print(a is c) # False (different object)
17. Custom exception handling
class MyError(Exception):
pass
try:
raise MyError("Something went wrong")
except MyError as e:
print(e)
18. Check if number is Armstrong
def is_armstrong(n):
return n == sum(int(d)**3 for d in str(n))
print(is_armstrong(153)) # True
19. Use pandas to filter CSV rows
import pandas as pd
df = pd.read_csv('[Link]')
filtered = df[df['age'] > 25]
print(filtered)
20. Demonstrate @staticmethod and @classmethod
class Example:
@staticmethod
def greet():
return "Hello"
@classmethod
def identity(cls):
return cls.__name__
print([Link]()) # Hello
print([Link]()) # Example