script_13.py - List Enumeration
Code
See script_13.py for full code.
Explanation
Line 9: for index, fruit in enumerate(fruits):
- enumerate() adds counter to iteration
- Returns tuples: (0, "apple"), (1, "banana"), etc.
- Tuple unpacking: index gets counter, fruit gets element
- Default counter starts at 0
Line 14: for num, fruit in enumerate(fruits, start=1):
- start=1 parameter changes starting index
- Counter becomes 1, 2, 3, 4 instead of 0, 1, 2, 3
- Useful for human-readable numbering
Line 20: data = ["100", "200", "invalid", "400", "bad"]
- Mixed list: some convertible to int, some not
Line 22: def process_number(value):
- Function that may raise exception
Line 25-26: Empty lists for results
- errors collects error messages
- results collects successful conversions
Line 28: for line_num, value in enumerate(data, start=1):
- Using enumerate to track position for error reporting
- line_num shows which input failed
Line 29-33: Try-except block
- try: attempts conversion
- except ValueError: catches conversion errors
- as e captures exception object
Line 32: errors.append(f"Line {line_num}: Invalid value '{value}'")
- Stores error with line number context
- Useful for debugging and user feedback
Line 39: positions = [i for i, x in enumerate(numbers) if x == target]
- List comprehension with enumerate
- Filters to matching elements
- Collects their indices
- Finds all positions of target value
Line 45: for rank, (name, score) in enumerate(zip(names, scores), start=1):
- Combines enumerate with zip
- Nested tuple unpacking: (name, score) from zipped pairs
- rank from enumerate
- Three variables from two functions
Line 51: tag_to_index = {tag: idx for idx, tag in enumerate(tags)}
- Dict comprehension with enumerate
- Creates reverse index (value -> position)
- Useful for lookups