Search code examples
pythoniterable-unpacking

Printing variable length unpacked items from iterable


I'm trying to unpack student name and marks from a record and print them. I'm seeing only 1st item in marks instead of whole list of marks.

records = [
    ("Name1", 1, 2, 3, 4 ,5),
    ("Name2", 2, 3, 8, 9, 10),
    ("Name3", 8, 9, 2, 3, 1)
    ]
for name, *marks in records:
    print("Name: {0}, Marks: {1}".format(name, *marks))`

Output:

Name: Name1, Marks: 1
Name: Name2, Marks: 2
Name: Name3, Marks: 8`

Why other values for marks are not printed? If I try to following, then whole list of marks is printed.

for name, *marks in records:
    print(name, *marks)`

Output:

Name1 1 2 3 4 5
Name2 2 3 8 9 10
Name3 8 9 2 3 1

Solution

  • The reason you only see the first item is because you did not specify a {2}, {3}, etc.

    You can however use str.join for example to join the remaining elements together, like:

    for name, *marks in records:
        print("Name: {0}, Marks: {1}".format(name, ' '.join(map(str, marks))))

    which will yield:

    Name: Name1, Marks: 1 2 3 4 5
    Name: Name2, Marks: 2 3 8 9 10
    Name: Name3, Marks: 8 9 2 3 1