Python Forum
iterating and detecting the last - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: iterating and detecting the last (/thread-38347.html)



iterating and detecting the last - Skaperen - Sep-30-2022

i am iterating over a list (or tuple). for each item except the last item i need to do a specific thing. for the last item i need to do something different. the solution i am thinking about is to get the initial len() of the list and count as the iterating proceeds. if the counting is up, i detect the last when the count equals the length. another way is iterating over range(len(seq)-1) and indexing the sequence like:
for x in range(len(seq)-1):
     foo(seq[x])
bar(seq[-1])
there are many ways to do this. which would be the best? which would be most pythonic?


RE: iterating and detecting the last - Yoriz - Sep-30-2022

items = [1, 2, 3, 4]

for item in items[:-1]:
    print(item)
print(f"last item = {items[-1]}")
Output:
1 2 3 last item = 4



RE: iterating and detecting the last - bowlofred - Sep-30-2022

If you know it's a sequence (which list and tuples are), I'd just iterate over obj[:-1].

If it's something that isn't a sequence (like a generator), then you could just stick the current object in a cache and operate on it after you read the next item.

for element in seq[:-1]:
    foo(element)
bar(seq[-1])
or:

i = iter(obj)
cache = next(i)
for item in i:
    foo(cache)
    cache = item
bar(cache)



RE: iterating and detecting the last - Gribouillis - Oct-01-2022

The cache strategy is also implemented in more_itertools.peekable()
for item in (p := peekable(iterable)):
    if not p:
        print(f"Item {item} is the last one")
    else:
         print("Not the last item")