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)
endPython
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
BeginnerThe 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Luau Developers
1From Luau to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler