How to check if an element is the last iteration in python

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 ', ' # word separator

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)
+4
source share
4 answers

if idx < len(list_x) - 1: , . , , .

def tag_last(iterable):
    """Given some iterable, returns (last, item), where last is only
    true if you are on the final iteration.
    """
    iterator = iter(iterable)
    gotone = False
    try:
        lookback = next(iterator)
        gotone = True
        while True:
            cur = next(iterator)
            yield False, lookback
            lookback = cur
    except StopIteration:
        if gotone:
            yield True, lookback
        raise StopIteration()

python 2 :

>>> for last, i in tag_last(xrange(4)):
...     print(last, i)
... 
(False, 0)
(False, 1)
(False, 2)
(True, 3)
>>> for last, i in tag_last(xrange(1)):
...     print(last, i)
... 
(True, 0)
>>> for last, i in tag_last(xrange(0)):
...     print(last, i)
... 
>>> 
+1

', '.join(['one', 'two', 'three', 'four', 'five']) - ;)

.

:

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

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

one, two, three, four, five

+5

( join, , ):

>>> print(*str_list, sep=', ')
one, two, three, four, five

sep print - . * list . ​​

EDIT:

, .

(range(len(a)) - 1), , , something_wrong() a (a[-1]) .

+3
source

If you are looking for a more generalized solution to skip the last element, this might be useful:

a = ['a','b','c','d']
for element,_ in zip( a, range(len(a) - 1) ):
    doSomethingRight(element)
doSomethingWrong(a[-1])

Explanation:
zipWill exit when the list of lists is shortened. Thus, looping on aand a rangeon one object whose length is less than the length, you will be doSomethingRight()for all elements except the last. Then call doSomethingWrong()for the last item.

In your example

str_list = ['one', 'two', 'three', 'four', 'five']
word_seperator = ","; string_end = "!"
result = ""
for element,_ in zip( str_list, range( len(str_list) - 1 ) ):
    result += element + word_seperator    # This is my 'doSomethingRight()'
result += str_list[-1] + string_end    # This is my 'doSomethingWrong()'

Result: one,two,three,four,five!

Hope this helps!

+2
source

Source: https://habr.com/ru/post/1535978/


All Articles