items and enumerate
Lesson 18 of 48 in Coddy's Python for R Developers course.
R loops over seq_along when positions are needed and can use names to recover labels. Python enumerate pairs each value with a counter, starting at zero by default or another explicit start. The counter is a label and does not skip elements. Direct Python dict iteration yields keys; items yields key/value pairs. This differs from iterating an R named list, where iteration visits element values without automatically binding each name. Use explicit names in R and explicit items in Python when both pieces matter. Do not add or remove dictionary keys while traversing its live view.
R
counts <- list(red=2)
for (key in names(counts)) cat(key, counts[[key]], "\n")
labels <- c("red", "blue")
for (i in seq_along(labels)) cat(i, labels[[i]], "\n")Python
counts = {'red': 2}
for key, value in counts.items():
print(key, value)
for index, value in enumerate(['red'], start=1):
print(index, value)Porting trap
Python enumerate yields index then value. A one-based display counter does not change the list's actual zero-based indexing.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler