Home > Software design >  How do I loop through a list and print each element separated by commas without the last comma?
How do I loop through a list and print each element separated by commas without the last comma?

Time:10-30

I'm trying to loop through the elements of a list, print them out, separate them by a comma but leave the trailing comma; all in a single loop. I'm aware of the join() method but I wanted to ask if there was a way to complete that within the loop?

This is the code I'm currently working with:

grades = [['A1', 12], ['A2', 18], ['A3', 20], ['A4', 19]]

for i in range(len(grades)):
    print(grades[i][0], end = ', ')

It keeps returning this:

A1, A2, A3, A4,

How do I stop that last comma from appearing?

CodePudding user response:

You can use print with sep parameter, or join:

grades = [['A1', 12], ['A2', 18], ['A3', 20], ['A4', 19]]

print(*(x[0] for x in grades), sep=', ') # A1, A2, A3, A4

print(', '.join(x[0] for x in grades)) # A1, A2, A3, A4

CodePudding user response:

I believe this should work:

grades = [['A1', 12], ['A2', 18], ['A3', 20], ['A4', 19]]

for i in range(len(grades)):
    print(grades[i][0], end = ', ' if i != len(grades) - 1 else '')

I achieved this using the ternary operator in Python. "i == len(grades) - 1" is True when i is the last index in the list.

I would also suggest checking out this previously asked question.

  • Related