For Loops and Indexing
While it's often better to iterate directly over items (as seen in the previous lesson), sometimes you need the index (position) of the item to perform actions like accessing multiple related sequences or modifying a sequence by index.
Using range(len(sequence))
We can combine len() (to get the total number of items) and range() (to generate indices from 0 up to the length).
python names = ['Alice', 'Bob', 'Charlie']
for index in range(len(names)): name = names[index] # Use the index to retrieve the item
# Conditional check based on index
if index == 0:
print(f"The boss is {name} at index {index}.")
else:
print(f"Employee {name} is at index {index}.")
Output:
The boss is Alice at index 0. Employee Bob is at index 1. Employee Charlie is at index 2.
Important: In most Python scenarios, direct iteration (for name in names:) is preferred for simplicity unless you specifically require the index.