Menu
CoddyTech

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

Practice on your own: Online Python compiler