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},')
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},')
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},')
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.
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