Python Interview Questions - Sandeep Kanao
Question 1: What is the difference between a list and a tuple?
A list is mutable, meaning it can be changed after it is created, while a tuple is immutable, meaning it cannot be changed after it is created. Here is an example:
# 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?
"==" checks for equality of values, while "is" checks for identity, meaning it checks if two variables refer to the same object in memory. Here is an example:
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?
A shallow copy creates a new object, but references the same objects as the original. A deep copy creates a new object and recursively copies all objects it references. Here is an example:
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
A decorator is a function that takes another function as input and extends the behavior of the latter function without explicitly modifying it. Here is an 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
Question 5: What is the difference between a generator and a list?
A generator generates values on-the-fly, while a list generates all values at once and stores them in memory. This makes generators more memory-efficient for large datasets. Here is an example:
# 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?
A module is a single file containing Python code, while a package is a directory containing one or more modules. A package must contain a file named "__init__.py" to be recognized as a package by Python. Here is an example:
# 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
A class is a blueprint for creating objects, while an object is an instance of a class. Here is an example:
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?
A static method is a method that belongs to a class, but does not have access to the class or instance. A class method is a method that belongs to a class and has access to the class, but not the instance. Here is an example:
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?
A try-except block catches and handles exceptions that occur within the block, while a try-finally block executes a block of code regardless of whether an exception occurs or not. Here is an example:
# 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?
A lambda function is an anonymous function that can be defined in a single line, while a regular function is a named function that can be defined in multiple lines. Here is an example:
# 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?
A list comprehension generates a list, while a generator expression generates a generator. A generator expression is more memory-efficient for large datasets. Here is an example:
# 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
A set is mutable, meaning it can be changed after it is created, while a frozenset is immutable, meaning it cannot be changed after it is created. Here is an example:
# 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?
A private attribute is an attribute that can only be accessed within the class that defines it, while a protected attribute is an attribute that can be accessed within the class that defines it and its subclasses. In Python, there is no true private attribute, but a convention is used to indicate that an attribute is private by prefixing it with an underscore. Here is an example:
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?
A file object is an object that represents a file that has been opened for reading or writing, while a file path is a string that represents the location of a file on the file system. Here is an example:
# 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?
A process is an instance of a program that is being executed, while a thread is a unit of execution within a process. A process can have multiple threads. Here is an example:
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?
A map applies a function to each element of an iterable and returns a new iterable with the results, while a filter applies a function to each element of an iterable and returns a new iterable with the elements for which the function returns True. Here is an example:
# 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
A dict is a dictionary that raises a KeyError if a key is not found, while a defaultdict is a dictionary that returns a default value if a key is not found. The default value is specified when the defaultdict is created. Here is an example:
# 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?
A list is a dynamic array that supports random access, while a deque is a double-ended queue that supports adding and removing elements from both ends in constant time. Here is an example:
# 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?
A coroutine is a function that can be paused and resumed, while a generator is a function that generates a sequence of values lazily. Coroutines are used for asynchronous programming, while generators are used for lazy evaluation. Here is an example:
# 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?
A context manager is an object that defines the methods "__enter__" and "__exit__", which are called when entering and exiting a "with" block, respectively. A decorator is a function that takes another function as input and extends the behavior of the latter function without explicitly modifying it. Here is an example:
# 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