Section 2 · Lesson 1

Lists and for loops

Keep many values in a list, then loop over them to total, filter and transform.

30 min 3 practice tasks
Python Tutorial for Beginners 4: Lists, Tuples, and Sets by Corey Schafer on YouTube

So far each variable held one value. Real data comes in bulk: a week of clicks, hundreds of orders, dozens of campaigns. A list holds many values in order, and a for loop lets you work through them one at a time.

Creating and reading lists

channels = ["search", "social", "display", "video"]
daily_clicks = [494, 486, 464, 540, 512, 478, 530]
empty = []

Lists use the same indexing and slicing as strings, starting at 0:

channels[0]         # 'search'
channels[-1]        # 'video'   (last item)
daily_clicks[1:3]   # [486, 464]
daily_clicks[-3:]   # [512, 478, 530]
len(channels)       # 4

Built-in helpers

Code Result What it does
sum(daily_clicks) 3504 add up numbers
max(daily_clicks) / min(...) 540 / 464 largest / smallest
sorted(daily_clicks) new sorted list ascending; add reverse=True for descending
"video" in channels True membership test
channels.index("display") 2 position of a value

Changing a list

Unlike strings, lists can be changed in place:

channels.append("audio")     # add to the end
channels[0] = "paid search"  # replace an item
channels.remove("audio")     # remove by value

The for loop

A for loop runs its indented block once per item, with the loop variable set to the current item:

for channel in channels:
    print(channel.upper())

Almost every loop you write in analysis follows one of three patterns.

Accumulate (build up a total):

total = 0
for clicks in daily_clicks:
    total = total + clicks      # or: total += clicks

Filter (keep only some items):

big_days = []
for clicks in daily_clicks:
    if clicks >= 500:
        big_days.append(clicks)
# big_days == [540, 512, 530]

Transform (compute something new for each item):

spend = [682.23, 613.15, 621.25]
spend_with_fee = []
for s in spend:
    spend_with_fee.append(round(s * 1.15, 2))   # add a 15% agency fee

Looping with positions: range, enumerate and zip

  • range(5) produces 0, 1, 2, 3, 4, which is handy for “do this 5 times”.
  • enumerate(items) gives you the position and the item: for day, clicks in enumerate(daily_clicks, start=1): print(f"Day {day}: {clicks}")
  • zip(a, b) walks two lists side by side, pairing items at the same position:
campaigns = ["Search", "Social"]
spend = [1250.0, 980.5]
for name, s in zip(campaigns, spend):
    print(f"{name}: ${s:,.2f}")

Tip: Parallel lists (like campaigns and spend above) work, but they break easily: sort one and forget the other, and every number is now attached to the wrong campaign. In the next lessons you’ll see better ways to keep related values together, first dictionaries, then pandas DataFrames.

A tuple, ("US", "CA"), is like a list you can’t change, and a set, {"US", "CA"}, keeps only unique values with no order. Lists are the one you will use most.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

A week of clicks

Here are one campaign's clicks for seven days, oldest first: daily_clicks = [494, 486, 464, 540, 512, 478, 530].

Using built-in functions and slicing, create:

  • total_clicks: the sum of all seven days
  • best_day_clicks: the highest single day
  • avg_clicks: the daily average, rounded to 1 decimal
  • last_three: a list with the last three days' clicks
Need a hint?
  1. sum(), max() and len() all accept a list.
  2. Average = total ÷ number of days; wrap it in round(..., 1).
  3. Negative indexes count from the end: daily_clicks[-3:] is the last three items.
Python 3
daily_clicks = [494, 486, 464, 540, 512, 478, 530]

total_clicks = 0
best_day_clicks = 0
avg_clicks = 0
last_three = []

print(total_clicks, best_day_clicks, avg_clicks, last_three)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

Filter orders with a loop

order_amounts = [38.92, 39.94, 15.84, 11.9, 249.5, 87.25, 120.0, 64.1]

Use a for loop with an if inside to build:

  • large_orders: a list of the amounts that are 50 or more, in their original order
  • large_total: the sum of those amounts, rounded to 2 decimals
Need a hint?
  1. Inside the loop: if amount >= 50: then large_orders.append(amount) (indented one more level).
  2. After the loop, round(sum(large_orders), 2) gives the total.
Python 3
order_amounts = [38.92, 39.94, 15.84, 11.9, 249.5, 87.25, 120.0, 64.1]

large_orders = []
for amount in order_amounts:
    pass  # replace this line

large_total = 0
print(large_orders, large_total)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Cost per click for each campaign

Three parallel lists describe three campaigns (same position = same campaign):

campaigns = ["Search", "Social", "Video"]
spend = [1250.0, 980.5, 2100.0]
clicks = [820, 610, 1750]

1. Build cpc_list: each campaign's cost per click (spend ÷ clicks), rounded to 2 decimals, in the same order as campaigns. 2. Set cheapest to the name of the campaign with the lowest CPC.

Need a hint?
  1. zip(spend, clicks) hands you one spend and one clicks value per loop: for s, c in zip(spend, clicks):.
  2. min(cpc_list) finds the lowest CPC; cpc_list.index(value) tells you its position.
  3. Use that position to look up the name in campaigns.
Python 3
campaigns = ["Search", "Social", "Video"]
spend = [1250.0, 980.5, 2100.0]
clicks = [820, 610, 1750]

cpc_list = []
cheapest = ""

print(cpc_list, cheapest)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country