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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

16 lines
Python 3.9+
def 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

stdout
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

  1. Use a list comprehension with `enumerate` for a one-liner: `['%d. %s: %d' % (i, name, grade) for i, (name, grade) in enumerate(students, 1)]`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.