Home > other >  comma after every element in list instead of the last one
comma after every element in list instead of the last one

Time:03-21

I want to make a function which would add comma after every word in list instead of the last one. I tried to do it with a while-loop so it could stop before the comma reaches the last word, but the output of the code is not doing its job.

list = ['Sadzo', 'Nimadaro', 'Duol']
wordIndex = 0
LenghtUnderIndex = len(list[wordIndex])

while wordIndex <= len(list):
  list.insert(LenghtUnderIndex, ', ')
  wordIndex  = 1
  break

print (*list)

CodePudding user response:

This is what join is for.

out = ','.join(list)

However, do not name your variable list. That hides the Python type by the same name.

CodePudding user response:

Why not just use:

for x in range(len(list) - 1):
  list[x] = list[x]   ","
  • Related