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].
- List: Mutable, can be changed after creation. Syntax:
[^1_2][^1_3][^1_4] - Tuple: Immutable, cannot be changed after creation. Syntax:
(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__ 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")*argsallows a function to accept any number of positional arguments.**kwargsallows 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 += 1You 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")- Shallow copy: Copies reference to objects only. Changes to nested objects affect both copies.
- Deep copy: Copies everything recursively. Changes in nested objects do not affect the original.
Example:
import copy
lst1 = [[1, 2], [3, 4]]
lst2 = copy.copy(lst1) # Shallow copy
lst3 = copy.deepcopy(lst1) # Deep copyThese questions and answers cover concepts commonly tested in Python interviews.