0

I have a loop where I print list items with commas. I want to use a comma with all items except for the last one. how do I do this?

digits = [1,2,3,4,5]
for i in digits:
   print(f'{i},')
Saadat Ali
  • 37
  • 5

4 Answers4

2

You should use str.join:

print(','.join(f'{i}' for i in digits))
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
1

I think this is what you are looking for:

digits = [1, 2, 3, 4, 5]
for i in digits:
    if(i == len(digits)):
        print(f'{i}')
    else:
        print(f'{i},')
Madison Courto
  • 1,231
  • 13
  • 25
0

Here's a fun example using the index!

digits = [1,2,3,4,5]
output = ""
for i in range(len(digits)):
    output += str(digits[i])
    if digits[i] != digits[-1]:
        output += ", "
print(output)

Fun fact, this will actually work with a list of any length, except 1, and even if the elements of the list are strings, or different ints than the example ones.

MegaEmailman
  • 505
  • 3
  • 11
0

you can check for the last elemnt :

digits = [1,2,3,4,5]
for i in digits:
    if i == digits[len(digits)-1]:
        print(f'{i}')
    else:
        print(f'{i},')

for string same code will do:

digits =  ['ali', 'khan', 'malang', 'new', 'baby'] 
for i in digits:
    if i == digits[len(digits)-1]:
        print(f'{i}')
    else:
        print(f'{i},')

output:

ali,
khan,
malang,
new,
baby
SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14