Menu
CoddyTech

pairs, ipairs, and items

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

Luau pairs walks table entries without a general sorted-order guarantee, while ipairs stops at the first missing sequence index. Python dict.items yields pairs in insertion order and direct dictionary iteration yields keys. enumerate adds a counter that can start at one without skipping data. A Python list’s None slot remains a real element, so traversal does not stop there as ipairs does at nil.

Luau example

local counts = {red = 2}
for key, value in pairs(counts) do print(key .. " " .. value) end
for index, label in ipairs({"red", "blue"}) do
    print(index .. " " .. label)
end

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

Do not modify dictionary size during iteration over its live views; collect keys to remove first.

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 Luau Developers

Practice on your own: Online Python compiler