Populating a List with a for Loop in Python
Building lists using for loops is a fundamental operation in data science. In 2026, knowing when to use a traditional for loop versus a list comprehension (or other modern alternatives) is key to writing clean, efficient, and readable code.
TL;DR — Modern Approaches
- Use list comprehensions for simple transformations
- Use a
forloop when logic is complex or involves multiple steps - Use
append()inside loops when building lists dynamically
1. Traditional for Loop with append()
scores = [85, 92, 78, 95, 88, 76, 91]
# Traditional way - using append
high_scores = []
for score in scores:
if score >= 90:
high_scores.append(score)
print(high_scores)
2. List Comprehension (Often Preferred)
# More Pythonic and usually faster
high_scores = [score for score in scores if score >= 90]
# With transformation
squared_high = [score ** 2 for score in scores if score >= 90]
3. Real-World Data Science Example
import pandas as pd
# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
"order_id": range(1001, 1001 + n),
"order_date": pd.date_range("2026-01-01", periods=n, freq="3D"),
"customer_id": rng.integers(101, 121, n),
"customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
"product_id": rng.integers(1, 9, n),
"region": rng.choice(["North", "South", "East", "West"], n),
"category": rng.choice(["Electronics", "Computers", "Books", "Home"], n),
"payment_method": rng.choice(["card", "cash", "wallet"], n),
"segment": rng.choice(["consumer", "business"], n),
"quantity": rng.integers(1, 6, n),
"amount": rng.uniform(50, 2500, n).round(2),
"discount": rng.choice([0.0, 0.05, 0.1, 0.2], n),
}).assign(
price=lambda d: (d["amount"] / d["quantity"]).round(2),
profit=lambda d: (d["amount"] * rng.uniform(0.05, 0.3, n)).round(2),
).assign(
ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)
df = pd.read_csv("sales_data.csv")
# Building a list of high-value transactions using a for loop
high_value_records = []
for row in df.itertuples():
if row.amount > 1500:
high_value_records.append({
"customer_id": row.customer_id,
"amount": row.amount,
"region": row.region,
"order_date": row.order_date
})
print(f"Found {len(high_value_records)} high-value transactions")
4. Best Practices in 2026
- Use list comprehensions for simple filtering and transformations
- Use a
forloop with.append()when the logic inside the loop is complex (multiple conditions, calculations, or side effects) - Prefer
itertuples()overiterrows()when iterating over DataFrames for performance - Consider generators (
yield) instead of lists when working with very large data - Initialize lists with
[]orlist()before appending
Building Lists Step by Step
The classic way to populate a list is to create an empty list and call append inside a for loop. It is easy to read, supports multiple statements per item, and is the right choice when the logic includes try/except, logging or several conditions.
For simple transformations, a list comprehension does the same job in one line and is usually a little faster. Both create the full list in memory; for very large data consider a generator instead.
Avoid inserting at the front of a list in a loop, because insert(0, x) moves every element each time. Append and reverse once at the end if you need the opposite order.
Worked Example: Loop and Comprehension Side by Side
We clean prices with a loop that handles errors, then do a simpler transformation with a comprehension.
raw = ["19.99", "5", "n/a", "7.50", ""]
prices = []
skipped = 0
for text in raw:
text = text.strip()
if not text:
continue
try:
prices.append(float(text))
except ValueError:
skipped += 1
print(prices, "skipped:", skipped)
with_tax = [round(p * 1.08, 2) for p in prices]
print(with_tax)
The loop handles empty strings and invalid text in separate ways and counts the skipped value. Once the data is clean, the comprehension adds tax in a single readable line.
Common Mistakes
- Forcing complex error handling into a comprehension.
- Using insert(0, x) in a loop.
- Building large lists when a generator would do.
- Creating the empty list inside the loop by mistake.
Quick Summary
- append in a loop suits complex logic.
- Comprehensions suit simple transformations.
- Avoid insert(0, x) in loops.
- Consider generators for very large data.
Conclusion
Populating lists with a for loop is a basic but essential skill in data science. In 2026, the best practice is to use list comprehensions for simple cases and traditional for loops with .append() when the logic becomes complex. Understanding when to use each approach helps you write code that is both readable and performant.
Next steps:
- Review your current code and replace simple list-building loops with list comprehensions where appropriate, while keeping complex logic in explicit
forloops