Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an item is the last one of iteration?

For example, I have a list of strings:

str_list =['one', 'two', 'three', 'four', 'five']

I want to print all of them on the screen with:

for c in str_list:
    print c
    print ', ' # word separator

which results in:

one, two, three, four, five,

Here, a comma is not necessary at the end of the line and I don't want to print it. How can I modify the code above 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 may be a more elegant way to handle this.

Edited: Maybe I thought I gave a too simple example. Suppose what if I should call function x() for each iteration except for the last one:

for idx, x in enumerate(list_x):
    if idx < len(list_x) - 1:
        something_right(x)
    else:
        something_wrong(x)
like image 239
Jeon Avatar asked Apr 10 '14 17:04

Jeon


1 Answers

Inside of ', '.join(['one', 'two', 'three', 'four', 'five']) there's some sort of iteration ;)

And this is actually the most elegant way.

Here's another one:

# Everything except the last element
for x in a[:-1]:
    print(x + ', ', end='')

# And the last element
print(a[-1])

Outputs one, two, three, four, five

like image 179
vaultah Avatar answered Sep 28 '22 06:09

vaultah