script_20.py - Enumerate Example with Index
Code
Python
#!/usr/bin/env python3
"""Enumerate example with index"""
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
Explanation
Line 4: fruits = ["apple", "banana", "cherry", "date"]
- List of strings
Line 6: for index, fruit in enumerate(fruits, start=1):
- enumerate() is built-in function that adds counter to iterable
- Returns tuples of (index, element)
- start=1 parameter makes counter start at 1 (default is 0)
- Tuple unpacking: index, fruit gets both values
- index gets the counter (integer)
- fruit gets the list element (string)
- Without enumerate: would need for i in range(len(fruits)) then fruits[i]
- More Pythonic than manual index tracking
Line 7: print(f"{index}. {fruit}")
- Both variables available from tuple unpacking
- Creates numbered list: "1. apple", "2. banana", etc.