Python Interview Guide (1)
Python Interview Guide (1)
Python is a high-level, interpreted programming language known for its simplicity and readability. It
supports multiple programming paradigms, including object-oriented, functional, and procedural. Python's
syntax is clean and allows developers to write fewer lines of code compared to other languages like Java or
C++.
Key features:
Variables in Python are declared by assigning a value using the = operator. Python does not require
specifying the data type explicitly.
x = 10
name = "Alice"
price = 10.5
1
Variables can be reassigned to different types.
• List: Mutable, ordered, and allows duplicate elements. Defined with square brackets [] .
• Tuple: Immutable, ordered, and allows duplicates. Defined with parentheses () .
• Set: Mutable, unordered, and does not allow duplicates. Defined with curly braces {} .
my_list = [1, 2, 3]
for item in my_list:
print(item)
6. What are Python’s conditional statements, and how are they used?
x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
• Reference counting
• Garbage collection for cyclic references
• Built-in memory allocators and deallocators
2
8. Explain the use of the len() function.
The len() function returns the number of items in an object such as a string, list, tuple, or dictionary.
len("hello") # 5
len([1, 2, 3]) # 3
a = [1, 2]
b = [1, 2]
a == b # True
a is b # False
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
11. What are Python functions, and how do you define them?
Functions are blocks of reusable code. Defined using the def keyword:
def greet(name):
return f"Hello, {name}"
3
12. What is the difference between *args and **kwargs ?
13. How is Python's for loop different from other programming languages?
Python's for loop iterates directly over items in a sequence (e.g., list, string), not index-based unless using
range() or enumerate() .
for i in range(3):
print(i) # 0 1 2
import math
print(math.sqrt(16)) # 4.0
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
4
return wrapper
@decorator
def say_hello():
print("Hello")
Use slicing:
s = "hello"
print(s[::-1]) # "olleh"
if 5 in [1, 2, 5]:
print("Found")
square = lambda x: x * x
print(square(5)) # 25
1. Explain the difference between shallow copy and deep copy in Python.
A shallow copy creates a new object, but does not create copies of nested objects; they still reference the
original. A deep copy creates a new object and recursively copies all nested objects.
import copy
original = [[1, 2], [3, 4]]
5
shallow = copy.copy(original)
deep = copy.deepcopy(original)
Comprehensions provide a concise way to create collections. They are more readable and efficient than
traditional loops.
Python uses automatic garbage collection based on reference counting and a cyclic garbage collector that
removes cycles of objects referencing each other.
The GIL is a mutex that protects access to Python objects, preventing multiple native threads from
executing Python bytecodes simultaneously. This simplifies memory management but can be a bottleneck
in CPU-bound multi-threaded programs.
6
7. Explain the difference between @staticmethod and @classmethod.
d1 = {'a': 1}
d2 = {'b': 2}
merged = {**d1, **d2}
Or use:
d1.update(d2)
def gen():
yield 1
yield 2
7
12. How do you use the with statement?
with open("file.txt") as f:
data = f.read()
13. What is Python's itertools module, and when would you use it?
itertools provides tools for efficient looping (e.g., combinations , permutations , cycle ,
chain ). Useful for handling large datasets and performance-critical tasks.
Use NumPy:
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = A + B
16. What are Python's metaclasses, and how are they used?
Metaclasses are classes of classes, defining how classes behave. You can use them to control class creation.
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
8
17. How do you perform unit testing?
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 3, 5)
import os
print(os.getcwd())
From NumPy:
[Advanced section to be continued next. Would you like to proceed with it now?]