Format Lists of Tuples into Numbered Lines in Python
This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.
Python code
16 linesdef format_students(students):
formatted = []
for i, student in enumerate(students, start=1):
name, grade = student
formatted.append(f"{i}. {name}: {grade}")
return "\n".join(formatted)
if __name__ == "__main__":
students = [
("Alice", 92),
("Bob", 85),
("Charlie", 78),
("Diana", 95),
]
print(format_students(students))
Output
1. Alice: 92
2. Bob: 85
3. Charlie: 78
4. Diana: 95
How it works
The for i, student in enumerate(students, start=1) loop iterates over the list while tracking the index i starting from 1. Each student is a tuple, which is unpacked into name and grade. The f-string f"{i}. {name}: {grade}" builds the formatted line. All lines are collected in formatted and joined with newlines using "\n".join(formatted), producing the final output.
Common mistakes
- Forgetting `start=1` in enumerate, resulting in 0-based numbering
- Not unpacking the tuple and trying to access `student[0]` and `student[1]` less cleanly
- Printing each line inside the loop instead of building a string for a single output
Variations
- Use a list comprehension with `enumerate` for a one-liner: `['%d. %s: %d' % (i, name, grade) for i, (name, grade) in enumerate(students, 1)]`
- Write to a file with `open('output.txt', 'w')` instead of printing
Real-world use cases
- Generating a printable grade report for students in an academic system.
- Formatting a list of users and emails for a CLI admin script.
- Creating numbered entries in a data export for CSV or email content.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.