Populating a List with a for Loop in Python

Data Science Tool Box Mar 18, 2026

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 for loop 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 for loop with .append() when the logic inside the loop is complex (multiple conditions, calculations, or side effects)
  • Prefer itertuples() over iterrows() when iterating over DataFrames for performance
  • Consider generators (yield) instead of lists when working with very large data
  • Initialize lists with [] or list() 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 for loops

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices