Learning LibraryCore Coding LibraryTeens

Lists in Python: a week of data in one variable

Seven days of sales shouldn't be seven variables. A list holds the whole week in order, and a handful of built-in functions turn it into answers.

The big idea

A list is an ordered collection of values under one name, which you can index, measure, and loop over.

See it in code

1The basics

Square brackets create a list. Indexing starts at 0, so [0] is the first item:

python
daily_tees = [42, 57, 38, 64, 71, 95, 88]
print("Launch week:", daily_tees)
print("First day:", daily_tees[0])
print("Days recorded:", len(daily_tees))
Run it. Launch week, day by day:
Launch week: [42, 57, 38, 64, 71, 95, 88]
First day: 42
Days recorded: 7

One variable, seven values. len() reports how many items the list holds, which is rarely worth typing in by hand.

2A step further

Built-in functions summarize a list in one call each:

python
daily_tees = [42, 57, 38, 64, 71, 95, 88]

total = sum(daily_tees)
print("Total tees:", total)
print(f"Average per day: {total / len(daily_tees):.1f}")
print("Best day:", max(daily_tees), "| Worst day:", min(daily_tees))
Run it. The week in four numbers:
Total tees: 455
Average per day: 65.0
Best day: 95 | Worst day: 38

Dividing by len(daily_tees) instead of a typed-in 7 keeps the average correct if the list ever grows. Hard-coded lengths are a bug waiting for new data.

3At Evergreen

Lists that line up by position can be combined. Revenue comes from one list, order counts from another, and together they give average order value:

python
daily_tees = [42, 57, 38, 64, 71, 95, 88]
daily_orders = [30, 41, 27, 45, 50, 66, 61]
price = 38

revenues = []
for tees in daily_tees:
    revenues.append(tees * price)

print("Daily revenue:", revenues)
print(f"Average order value: ${sum(revenues) / sum(daily_orders):.2f}")
Run it. What does a typical order bring in?
Daily revenue: [1596, 2166, 1444, 2432, 2698, 3610, 3344]
Average order value: $54.03

The loop builds a new list from an old one, a pattern you'll use constantly. Total revenue divided by total orders gives about $54 an order, more than one tee's worth.

The same idea, everywhere

Almost every dataset is a list underneath: closing prices by day, readings from a sensor, the rows of a table, the bases along a chromosome.

Try it yourself

Append an eighth day with daily_tees.append(72) before the totals are computed, and watch the average move. Then find which day number was best, not just how many tees it sold.

The common mistake

Summarizing before the data is complete. sum(daily_tees) counts the list as it is at that moment, so an append on a later line isn't included. Gather the data first, then compute.

What it unlocks

Reach into a list with indexing and slices, change it with list methods, and when positions stop being meaningful, switch to a dictionary.

Want the simpler version? Read the Kids version →