Loop with index

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

for Loop

JS · Control Flow
Syntax
for (init; condition; update) { ... }
Example
const items = ["apple", "banana", "cherry"];
for (let i = 0; i < items.length; i++) {
  console.log(`${i + 1}. ${items[i]}`);
}
Output
"1. apple"
"2. banana"
"3. cherry"

Note Classic loop when you need the index. For simple iteration, prefer for...of. Cache .length in the initializer if the array is very large and not changing.

PYPython

Useful List Operations

PY · Lists
Syntax
len() / in / enumerate() / zip()
Example
items = ["pen", "notebook", "eraser"]
print(len(items))
print("pen" in items)

for idx, item in enumerate(items, start=1):
    print(f"{idx}. {item}")
Output
3
True
1. pen
2. notebook
3. eraser

Note enumerate() gives (index, value) pairs. Pass start= to begin counting from a number other than 0.

Frequently asked questions

How do you loop with index?
This task is covered in 2 stacks on this page: JavaScript, Python. The "for Loop" snippet in JavaScript uses `for (init; condition; update) { ... }`.
Which code does the JavaScript example use?
The "for Loop" snippet uses `for (init; condition; update) { ... }`, from the Control Flow section of the JavaScript cheat sheet.
Which stacks cover "loop with index" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "for Loop": Classic loop when you need the index. For simple iteration, prefer for...of. Cache .length in the initializer if the array is very large and not changing.