← Python lessons

Accumulator Starting Values: 1, Empty Text and Dictionaries

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

An accumulator's starting value must leave the first update unchanged: 0 for a sum, 1 for a product, "" for text and {} for a tally.

Read The Accumulator Pattern first. You should also know Dictionaries.

This lesson shows three accumulators that do not start at 0, and the mistake each wrong start causes. Every block runs on its own with fixed data, and the text under it says what it prints.

Multiply with a product

A product starts at 1, because multiplying by 1 changes nothing.

product = 1
for number in [2, 3, 4]:
    product = product * number
print(product)

This prints 24. Starting at 0 would print 0, because anything times 0 is 0.

Build text one piece at a time

Text starts as the empty string "". Adding a string to it joins the two.

initials = ""
for name in ["Ada", "Sam", "Lee"]:
    initials = initials + name[0]
print(initials)

This prints ASL. Starting at 0 would raise TypeError: Python cannot add a string to a number.

try:
    initials = 0
    initials = initials + "A"
except TypeError:
    print("Start text at an empty string")

Tally values in a dictionary

A tally counts each different value separately. Start with an empty dictionary. Add a key the first time you see a value.

tally = {}
for roll in [3, 6, 3, 1, 6, 3]:
    if roll in tally:
        tally[roll] = tally[roll] + 1
    else:
        tally[roll] = 1
print(tally)

This prints {3: 3, 6: 2, 1: 1}. Without the if, the first tally[roll] + 1 raises KeyError, because the key is not there yet.

roll in tally checks the dictionary's keys, not its values. Use in to choose between adding 1 to an old key and creating a new key.

Note: These examples leave out empty input. With an empty list, the loop never runs, so you get the starting value back: 1, "" or {}. Decide whether that answer makes sense for your program.

See also: Augmented assignment, Built-in accumulators.

Your turn

Use one loop over words. Build joined, the words joined with no spaces. Build counts, a dictionary of how many times each word appears. Print both.

words = ["hi", "yo", "hi"]
joined = ""
counts = {}
# add a loop that updates joined and counts, then print joined and counts

Expected output

hiyohi
{'hi': 2, 'yo': 1}