Python Forum
iterating and detecting the last
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iterating and detecting the last
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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
Skaperen likes this post
Reply
#3
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)
Skaperen likes this post
Reply
#4
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")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Detecting float or int in a string Clunk_Head 15 4,586 May-26-2022, 11:39 PM
Last Post: Pedroski55
  module detecting if imported vs not Skaperen 1 1,683 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  detecting a generstor passed to a funtion Skaperen 9 3,633 Sep-23-2021, 01:29 AM
Last Post: Skaperen
  Python BLE Scanner not detecting device alexanderDennisEnviro500 0 2,015 Aug-01-2021, 02:29 AM
Last Post: alexanderDennisEnviro500
  Detecting power plug Narayan 2 2,727 Aug-01-2020, 04:29 AM
Last Post: bowlofred
  Detecting USB Device Insertion on Windows 10 Atalanttore 0 2,401 Jan-17-2020, 02:46 PM
Last Post: Atalanttore
  Detecting windows shutdown event riccardoob 4 5,739 Nov-12-2019, 04:51 PM
Last Post: Aurthor_King_of_the_Brittons
  Detecting String Elements in a List within Given Message Redicebergz 6 3,833 Mar-19-2019, 03:12 PM
Last Post: buran
  Detecting if image matches another kainev 2 2,916 Dec-02-2018, 02:00 PM
Last Post: kainev
  Detecting file extensions ellipsis 1 2,302 Nov-15-2018, 07:44 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020