Module 2 · Python for Data · Lesson 5 of 51

Lists, dictionaries and loops

Store many values in lists and dictionaries, loop over them, count and total things, and write compact list and dict comprehensions.

In this lesson · about 40 minutes

  • Create, index, slice and change lists
  • Use a dictionary to look up and total values by key
  • Loop with for, and write list comprehensions

Lists

totals = [4.5, 9.0, 3.25]. Positions start at 0: totals[0] is 4.5 and totals[-1] is the last item. Slicing takes a range: totals[0:2] gives items 0 and 1 (the end is not included). Useful tools: len(), sum(), min(), max(), sorted(), .append(x).

Dictionaries

prices = {"Latte": 4.5, "Muffin": 3.0} maps keys to values. prices["Latte"] looks up a value; prices["Bagel"] = 4.25 adds one; prices.get("Tea", 0) returns 0 instead of crashing when the key is missing. Loop over pairs with for item, price in prices.items():.

Loops

A for loop runs its indented block once per item. The accumulator pattern (start a total at 0, add inside the loop) is the hand-made version of what sum() and pandas' groupby do for you.

by_branch = {}
for branch, total in orders:
    by_branch[branch] = by_branch.get(branch, 0) + total

Comprehensions

A list comprehension builds a list in one line: [t * 1.1 for t in totals] (every total plus 10%), or with a filter, [t for t in totals if t > 5]. A dict comprehension works the same way: {item: p * 1.1 for item, p in prices.items()}.

Tuples and sets

A tuple ("Latte", 4.5) is a list that can't change, handy for fixed pairs. A set keeps only unique values: set(["Card", "App", "Card"]) is {"Card", "App"}.

Lists, dicts and the accumulator pattern

Exercise

Count payment methods

Build a dictionary counts that maps each payment method to how many times it appears in payments. Use a loop (or a comprehension).

Exercise

Price rise with a comprehension

Prices are going up 8%. Make new_prices, a dictionary with the same items and each price × 1.08 rounded to 2 decimals. Then make premium, a list of the item names whose new price is above 4.5, in the same order as the dictionary.

Check your understanding0 of 4 correct

Question 1

1.totals = [4, 9, 3, 8]. What is totals[1:3]?

Question 2

2.Why use d.get(key, 0) instead of d[key]?

Question 3

3.What does [x * 2 for x in [1, 2, 3] if x > 1] give?

Question 4

4.Which keeps only unique values?

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.