By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
A Hyper-Practical, Zero-Fluff Study Guide
You’re working on a data pipeline that processes millions of rows from a CSV, applies transformations, and exports results to a database. Your teammate wrote a 500-line script with duplicated logic, hardcoded values, and no error handling. The script fails silently when the input format changes, and debugging takes hours.
Functions, lambda expressions, and scope are your tools to: - Eliminate duplication (DRY principle).- Make code reusable (e.g., a clean_data() function used across multiple notebooks).- Control side effects (e.g., avoiding global variables that break reproducibility).- Write concise, readable transformations (e.g., df['column'].apply(lambda x: x.strip())).
clean_data()
df['column'].apply(lambda x: x.strip())
Real-world scenario:You inherit a Jupyter notebook where every transformation is copy-pasted. You need to refactor it into modular functions to: - Add unit tests.- Deploy it as a serverless AWS Lambda for scheduled runs.- Share it with your team without breaking existing workflows.
If you ignore these concepts, your code becomes: - Unmaintainable (e.g., fixing a bug in one place but missing 10 others).- Unscalable (e.g., a 10-line script becomes 1,000 lines of spaghetti).- Unreliable (e.g., global variables causing race conditions in parallel processing).
def
preprocess_text()
def foo(param):
foo("hello")
def foo(param: str) -> int:
return result
None
lambda
lambda x: x * 2
df['column'].apply(lambda x: x.upper())
*args
kwargs
def foo(*args):
def foo(kwargs):
plot_data()
def foo(x=1):
def foo(x=[]):
@timing
map()
filter()
sorted()
key
"""Returns x squared."""
help()
data.csv
id
name
value
timestamp
pip install pandas
Refactor a messy script into modular functions with proper scope and lambda expressions.
import pandas as pd df = pd.read_csv("data.csv") df["value"] = df["value"].str.replace("$", "").astype(float) df["timestamp"] = pd.to_datetime(df["timestamp"]) df = df[df["value"] > 0] df["name"] = df["name"].str.strip().str.title() df.to_csv("cleaned_data.csv", index=False)
str.replace
str.strip
str.title
astype(float)
pd.to_datetime
df[df["value"] > 0]
import pandas as pd def clean_currency(value: str) -> float: """Remove $ and convert to float.""" return float(value.replace("$", "")) def clean_text(text: str) -> str: """Strip whitespace and title-case text.""" return text.strip().title() def filter_positive(df: pd.DataFrame, column: str) -> pd.DataFrame: """Filter rows where column > 0.""" return df[df[column] > 0]
def preprocess_data(input_path: str, output_path: str) -> None: """Clean and filter data, then save to CSV.""" df = pd.read_csv(input_path) # Apply transformations df["value"] = df["value"].apply(clean_currency) df["timestamp"] = pd.to_datetime(df["timestamp"]) df = filter_positive(df, "value") df["name"] = df["name"].apply(clean_text) # Save df.to_csv(output_path, index=False) # Run the pipeline preprocess_data("data.csv", "cleaned_data.csv")
# Replace clean_text with a lambda (if logic is simple) df["name"] = df["name"].apply(lambda x: x.strip().title())
head cleaned_data.csv
Expected output:
id,name,value,timestamp 1,Alice,100.0,2023-01-01 2,Bob,200.0,2023-01-02
df
@functools.lru_cache
def foo(x: int) -> str:
logging.info("Processing %s rows", len(df))
assert df["value"].dtype == float
def foo(x=None): x = x or []
lambda x: x if x > 0 else 0
df.dropna()
inplace=True
try-except
Answer: For short, one-off operations (e.g., sorted(df, key=lambda x: x["value"])).
sorted(df, key=lambda x: x["value"])
Scope:
python x = 10 def foo(): x = 20 print(x) foo() print(x)
Answer: 20 (local scope), then 10 (global scope).
20
10
Default Arguments:
python def foo(x=[]): x.append(1) return x
Answer: The list retains state between calls (e.g., foo() returns [1], then [1, 1]).
foo()
[1]
[1, 1]
*args and kwargs:
Task:Write a function that: 1. Takes a pandas DataFrame and a column name.2. Returns a new DataFrame with rows where the column’s value is in the top 10%.3. Use a lambda to calculate the threshold.
Solution:
def top_10_percent(df: pd.DataFrame, column: str) -> pd.DataFrame: threshold = df[column].quantile(0.9) return df[df[column].apply(lambda x: x >= threshold)]
Why it works:- quantile(0.9) calculates the 90th percentile.- The lambda filters rows where the value is >= the threshold.
quantile(0.9)
def foo(x): return x * 2
def foo(): x = 1
x
foo
x = 1; def foo(): print(x)
def foo(*args): print(args)
def foo(kwargs): print(kwargs)
def foo(x=1): return x
x=[]
def outer(): x = 1; return lambda: x
apply()
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.