Top 10 Python Interview Questions W
Top 10 Python Interview Questions W
Solution:
Solution:
A concise way to create lists using a single line of code.
Example:
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Solution:
is checks for object identity (whether two references point to the same object).
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, values are equal
print(a is b) # False, different objects
Solution:
Using try, except, else, and finally blocks.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No error occurred.")
finally:
print("This block runs regardless of an error.")
5. What are Python decorators and why are they used?
Solution:
Decorators are functions that modify the behavior of other functions or methods.
They are used for adding functionality without changing the original function's
code. Example:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Solution:
A generator is a function that uses yield to return an iterator, which generates
values on the fly without storing them in memory. Example:
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
for value in gen:
print(value)
Solution:
Solution:
my_list = [1, 2, 3]
my_list.append([4, 5]) # [1, 2, 3, [4, 5]]
my_list.extend([6, 7]) # [1, 2, 3, [4, 5], 6, 7]
Solution:
A lambda function is an anonymous function defined using the lambda keyword. It's
often used for short, simple operations. Example:
Solution:
The GIL is a mutex in CPython (the standard Python implementation) that prevents
multiple native threads from executing Python bytecode at the same time. This can
limit the performance of multithreaded Python programs in CPU-bound operations but
not in I/O-bound operations.