For example, I have a list of strings:
str_list =['one', 'two', 'three', 'four', 'five']
I want to print everything on the screen with:
for c in str_list:
print c
print ', '
that leads to:
one, two, three, four, five,
Here the comma is not needed at the end of the line, and I do not want to print it. How to change the code above so as not to print the last comma?
It can be solved with enumerate:
for idx, c in enumerate(str_list):
print c
if idx < len(str_list) - 1:
print ','
However, I think there might be a more elegant way to handle this.
Edited: Maybe it seemed to me that I gave a too simple example. Suppose if I should call the x () function for each iteration, except for the last:
for idx, x in enumerate(list_x):
if idx < len(list_x) - 1:
something_right(x)
else:
something_wrong(x)