bhylu.com

Advertisements

Loop Lists

A for loop visits a list's elements in order. Use enumerate when you also need a position or displayed item number.

Understand the idea

The loop variable is bound to each element; changing that local name alone does not replace the element in the list. A starting count of 1 suits display numbering, while the sequence's real indices still start at zero. Keep mutation separate from traversal when possible.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

for number, topic in enumerate(["HTML", "CSS", "Python"], start=1):
    print(number, topic)

Read the result

The output numbers the three topics from 1 through 3.

Try one change

Print the same list without numbering, then explain which version the interface actually needs.