One problem with if idx < len(list_x) - 1:
is that it only works with sequences and not more generically with any iterator. You could write your own generator that looks ahead and tells you whether you've reached the end.
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()
In python 2 it would look like:
>>> 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)
...
>>>