Menu
CoddyTech

enumerated to enumerate

Lesson 18 of 48 in Coddy's Python for Swift Developers course.

Swift enumerated yields offsets with elements; Python enumerate does the same and accepts a custom starting counter. That start changes numbering, not where iteration begins. Python dictionary iteration alone yields keys; items yields key/value pairs. For Swift collections with noninteger indexes, an enumerated offset is not necessarily a collection index, while Python list indexing uses integer positions. Avoid changing dictionary size while iterating a live items view.

Swift example

let counts = ["red": 2]
for (key, value) in counts { print(key, value) }
for (index, label) in ["red", "blue"].enumerated() {
    print(index + 1, label)
}

Python

counts = {"red": 2}
for key, value in counts.items():
    print(key, value)
for index, label in enumerate(["red", "blue"], start=1):
    print(index, label)

Porting trap

When output requires a key order, sort explicitly instead of assuming a Swift Dictionary traversal order carries into Python.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

The single input line contains zero or more lowercase words separated by spaces. The supplied split() scaffold makes labels. Print one line per label as its one-based position, one space, then the label. Then print counts on its own line, followed by each distinct label and its frequency separated by one space, in first-seen order. Empty input prints only counts.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Swift Developers

Practice on your own: Online Python compiler