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.