Python Fundamentals
These are the Python concepts that show up constantly in AI, ML, and DL work — and just as importantly, the ones you should be comfortable explaining during a technical interview.
The goal is not to memorize syntax. The goal is to understand what the code is doing well enough that you can explain it, modify it, debug it, and write a small version of it under pressure.
For every concept below, ask yourself three questions: What does it do? Why would I use it? What happens if I change it?
Lists store ordered collections of values. In ML code, they appear in preprocessing, filtering, batching, feature construction, and quick data transformations.
Interview check:Be able to convert a normal loop into a list comprehension and explain when readability is more important than making the code shorter.
squares = [x**2 for x in range(5)]
# Same idea written normally:
squares = []
for x in range(5):
squares.append(x**2)Dictionaries store information as key-value pairs. They are everywhere in ML projects: configurations, label mappings, model outputs, hyperparameters, and experiment results.
Interview check:Know how to access, update, loop through, and safely retrieve dictionary values using .get().
config = {
"lr": 0.001,
"epochs": 10
}
print(config["lr"])
config["epochs"] = 20
batch_size = config.get("batch_size", 32)Tuples often represent fixed groups of values. Unpacking lets you pull those values apart cleanly.
Interview check:Understand whybatch_size, channels, height, width = x.shapeis useful and what error occurs if the number of values does not match.
shape = (32, 3, 224, 224)
batch_size, channels, h, w = shape
print(batch_size)
# 32Functions organize reusable logic. Training loops, preprocessing steps, evaluation functions, and model utilities are usually built from small reusable functions.
Interview check:Be able to explain parameters, return values, default arguments, and why mutable default arguments can be dangerous.
def train(model, epochs=10, lr=0.001):
print(f"Training for {epochs} epochs")
print(f"Learning rate: {lr}")*args collects extra positional arguments.**kwargs collects extra named arguments.
Interview check:Be able to explain the difference between positional arguments and keyword arguments.
def example(*args, **kwargs):
print(args)
print(kwargs)
example(1, 2, lr=0.001, epochs=10)Classes let us group data and behavior together. In deep learning, models are usually represented as objects.
Interview check:Be able to explain what self, __init__, inheritance, and super() are doing.
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)enumerate() gives you both the position and the value while looping.
Interview check:Know why enumerate() is usually cleaner than manually maintaining a counter.
losses = [0.9, 0.6, 0.3]
for epoch, loss in enumerate(losses):
print(epoch, loss)zip() lets you loop through multiple collections together.
Interview check:Know what happens if the collections have different lengths.
predictions = [1, 0, 1]
labels = [1, 1, 1]
for pred, label in zip(predictions, labels):
print(pred, label)Lambda functions are small anonymous functions used when a full function definition would be unnecessary.
Interview check:Know the syntax, but also know when a normal function would be more readable.
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))Real ML pipelines fail: missing files, invalid inputs, corrupt samples, bad API responses, and shape mismatches all happen.
Interview check:Understand try, except, and why catching every error with a bare except is usually a bad idea.
try:
value = int(user_input)
except ValueError:
print("Input must be a number.")Decorators modify the behavior of a function without changing the function itself.
Interview check:You do not always need to implement a decorator from scratch, but you should understand what the @ syntax means.
@torch.no_grad()
def evaluate(model, x):
return model(x)Generators produce values one at a time instead of storing everything in memory at once.
Interview check:Be able to explain why yield can use less memory than returning one huge list.
def batches(data, batch_size):
for i in range(0, len(data), batch_size):
yield data[i:i + batch_size]Python Interview Questions You Should Be Able to Answer
- What is the difference between a list and a tuple?
- What is the difference between
==andis? - What is the difference between a shallow copy and a deep copy?
- What are mutable and immutable objects?
- What do
*argsand**kwargsdo? - What does
selfmean inside a Python class? - What does
super()do? - What is a generator and why would you use one?
- What is the difference between
append()andextend()? - What happens when you assign one list to another variable?
- What is a dictionary lookup and why is it usually fast?
- What is the difference between
range()and a list? - What does a decorator do?
- Why are exceptions useful?
- What is the difference between a method and a function?
The Standard You Want
You are interview-ready when you can do more than recognize the syntax.
You should be able to look at a short piece of Python code and:
- Explain what it does line by line.
- Predict its output before running it.
- Find a bug or edge case.
- Rewrite it in a cleaner way.
- Explain why you chose one data structure over another.
- Connect the Python concept to how it appears in ML code.
Syntax gets you through the code. Understanding gets you through the interview.