How do I get both the position and value while looping over a list?
Quick answer
In Python, unpack enumerate(items) into two loop variables: the first is the zero-based position and the second is the value. To start a displayed count at 1, use enumerate(items, start=1). That changes the counter yielded by enumerate(), not the list’s underlying positions. If you need both numbers, keep them distinct—for example, subtract 1 from a count that starts at 1 to get the corresponding zero-based position.
The question, the details, the next step.
A practical checklist
Use
enumerate(items)for a zero-based position and value.Use
enumerate(items, start=1)for a display number starting at 1.Name the first variable
indexornumberaccording to what it represents.If you need both, keep the display number and zero-based position distinct.
Check whether later code expects a position or a display count.
A few more useful answers
Does `start=1` change the list itself?
No. It changes the counter yielded by enumerate(); it does not change the list’s items or underlying positions. [S1]
Do I need to increment a counter manually?
Not for this pattern. enumerate() yields a counter alongside each item, so you can unpack both in the loop. [S1]
What should I call the first loop variable?
Use index when it represents a zero-based position and number when it represents a display count starting at 1.
Sources
References used for this guide.
- [S1] Python Tutorial: Looping Techniques docs.python.org · Checked
