Here are the top 10 Python interview questions with concise answers and code examples where applicable:
Python is a high-level, interpreted, general-purpose programming language known for its simple, readable syntax. Key features include dynamic typing, automatic memory management, extensive libraries, and support for multiple programming paradigms (object-oriented, procedural, and functional)[^1_1].
Python uses automatic memory management with a built-in garbage collector. Memory is allocated and deallocated automatically as objects are created and destroyed. Reference counting and cyclic garbage collection are employed to manage and free memory efficiently[^1_1].
[^1_2][^1_3][^1_4](1, 2, 3)Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[^1_0] = 4 # Valid
# my_tuple[^1_0] = 4 # Raises TypeError
__init__ method in Python classes?__init__ is the constructor method that initializes a new class instance’s attributes when the object is created.
Example:
class Dog:
def __init__(self, name):
self.name = name
d = Dog("Buddy")
*args allows a function to accept any number of positional arguments.**kwargs allows any number of keyword arguments.Example:
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, three=3, four=4)
# Output: (1, 2), {'three': 3, 'four': 4}
List comprehensions provide a concise way to create lists using a single line of code.
Example:
squares = [x*x for x in range(6)]
# Output: [0, 1, 4, 9, 16, 25]
A decorator is a function that modifies the behavior of another function without changing its code, usually prefixed with @.
Example:
def decorator_func(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator_func
def say_hello():
print("Hello!")
say_hello()
A generator is a function that returns an iterator which yields one value at a time, using the yield statement. Generators don’t store all values in memory, making them memory efficient.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
You use try, except, else, and finally blocks to handle exceptions.
Example:
try:
x = 1 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("Execution complete")
Example:
import copy
lst1 = [[1, 2], [3, 4]]
lst2 = copy.copy(lst1) # Shallow copy
lst3 = copy.deepcopy(lst1) # Deep copy
These questions and answers cover concepts commonly tested in Python interviews.