Populating a List with a for Loop in Python – Best Practices for Data Science 2026
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
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
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