Python Interview Questions - Sandeep Kanao
Question 1: What is the difference between a list and a tuple?
# List example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
# Tuple example
my_tuple = (1, 2, 3)
my_tuple.append(4) # This will result in an error
Question 2: What is the difference between "is" and "==" in Python?
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # Output: True
print(a is b) # Output: False
print(a is c) # Output: True
Question 3: What is the difference between a shallow copy and a deep copy?
import copy
# Shallow copy example
original_list = [[1, 2, 3], [4, 5, 6]]
new_list = copy.copy(original_list)
new_list[0][0] = 0
print(original_list) # Output: [[0, 2, 3], [4, 5, 6]]
# Deep copy example
original_list = [[1, 2, 3], [4, 5, 6]]
new_list = copy.deepcopy(original_list)
new_list[0][0] = 0
print(original_list) # Output: [[1, 2, 3], [4, 5, 6]]
Question 4: What is a decorator in Python? - Sandeep Kanao
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello() # Output: Before function call\nHello\nAfter function call
Question 5: What is the difference between a generator and a list?
# List example
my_list = [i**2 for i in range(1000000)] # Generates all values at once
print(sum(my_list)) # Output: 333332833333500000
# Generator example
my_generator = (i**2 for i in range(1000000)) # Generates values on-the-fly
print(sum(my_generator)) # Output: 333332833333500000
Question 6: What is the difference between a module and a package?
# Module example
# File name: my_module.py
def my_function():
print("Hello from my_module")
# Package example
# Directory structure:
# my_package/
# __init__.py
# my_module.py
# File name: my_package/__init__.py
from .my_module import my_function
Question 7: What is the difference between a class and an object? Sandeep Kanao
class MyClass:
def __init__(self, x):
self.x = x
my_object = MyClass(5)
print(my_object.x) # Output: 5
Question 8: What is the difference between a static method and a class method?
class MyClass:
x = 5
@staticmethod
def my_static_method():
print("This is a static method")
@classmethod
def my_class_method(cls):
print("This is a class method with x =", cls.x)
MyClass.my_static_method() # Output: This is a static method
MyClass.my_class_method() # Output: This is a class method with x = 5
Question 9: What is the difference between a try-except block and a try-finally block?
# Try-except example
try:
x = 1/0
except ZeroDivisionError:
print("Cannot divide by zero")
# Try-finally example
try:
x = 1/0
finally:
print("This will always execute")
Question 10: What is the difference between a lambda function and a regular function?
# Regular function example
def my_function(x):
return x**2
# Lambda function example
my_lambda_function = lambda x: x**2
Question 11: What is the difference between a list comprehension and a generator expression?
# List comprehension example
my_list = [i**2 for i in range(1000000)] # Generates a list
print(sum(my_list)) # Output: 333332833333500000
# Generator expression example
my_generator = (i**2 for i in range(1000000)) # Generates a generator
print(sum(my_generator)) # Output: 333332833333500000
Question 12: What is the difference between a set and a frozenset? Sandeep Kanao
# Set example
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
# Frozenset example
my_frozenset = frozenset({1, 2, 3})
my_frozenset.add(4) # This will result in an error
Question 13: What is the difference between a private and a protected attribute?
class MyClass:
def __init__(self):
self._private_attribute = 5
self.__protected_attribute = 10
class MySubclass(MyClass):
def __init__(self):
super().__init__()
print(self._private_attribute) # Output: 5
print(self.__protected_attribute) # This will result in an error
Question 14: What is the difference between a file object and a file path?
# File object example
with open("my_file.txt", "r") as f:
print(f.read())
# File path example
import os
file_path = os.path.join("my_directory", "my_file.txt")
with open(file_path, "r") as f:
print(f.read())
Question 15: What is the difference between a thread and a process?
import threading
def my_function():
print("Hello from thread", threading.current_thread().name)
# Process example
import multiprocessing
process = multiprocessing.Process(target=my_function)
process.start()
# Thread example
thread = threading.Thread(target=my_function)
thread.start()
Question 16: What is the difference between a map and a filter?
# Map example
my_list = [1, 2, 3]
new_list = list(map(lambda x: x**2, my_list))
print(new_list) # Output: [1, 4, 9]
# Filter example
my_list = [1, 2, 3]
new_list = list(filter(lambda x: x%2 == 0, my_list))
print(new_list) # Output: [2]
Question 17: What is the difference between a dict and a defaultdict? Sandeep Kanao
# Dict example
my_dict = {"a": 1, "b": 2}
print(my_dict["c"]) # This will result in a KeyError
# defaultdict example
from collections import defaultdict
my_defaultdict = defaultdict(int, {"a": 1, "b": 2})
print(my_defaultdict["c"]) # Output: 0
Question 18: What is the difference between a list and a deque?
# List example
my_list = [1, 2, 3]
my_list.append(4)
my_list.pop(0)
print(my_list) # Output: [2, 3, 4]
# Deque example
from collections import deque
my_deque = deque([1, 2, 3])
my_deque.append(4)
my_deque.popleft()
print(my_deque) # Output: deque([2, 3, 4])
Question 19: What is the difference between a coroutine and a generator?
# Generator example
def my_generator():
for i in range(5):
yield i
for value in my_generator():
print(value) # Output: 0\n1\n2\n3\n4
# Coroutine example
async def my_coroutine():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(my_coroutine()) # Output: Hello\n[1 second delay]\nWorld
Question 20: What is the difference between a context manager and a decorator?
# Context manager example
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with MyContextManager():
print("Inside context")
# Decorator example
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello() # Output: Before function call\nHello\nAfter function call
No comments:
Post a Comment