Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get the first and last element of a python iterator

I'm trying to perform checks on the first and last elements of an interator. It has several thousand entries, so I need an expeditious method of checking. If found this post, that put me onto this strategy.

first = True
for value in iterator:
   if first:
      do_stuff_to_first_iter
      first = False
   else:
      pass
do_stuff_to_last_iter

Anyone have any opinions on a quicker method of accomplishing this? Thanks a lot!

like image 301
Rich Avatar asked Nov 20 '13 19:11

Rich


People also ask

How do I get the last element in iterator?

To get the last element in an iterator loop you can use std::next() (from C++11). The loop is generally terminated by iterator != container. end() , where end() returns an iterator that points to the past-the-end element.

How to print the last item in a list Python?

To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

How to get the last element of an array Python?

The best way to get the last element of a list in Python is using the list[-1]. Python allows you to use negative indices, which count from the end of the list instead of the beginning. So list[-1] gets the last element, list[-2] gets the second to last.

How to refer to the last item in a list Python?

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.


2 Answers

Get the first value with the next() function:

first = last = next(iterable, defaultvalue)
for last in iterable:
    pass

This assumes the iterable is finite.

For an empty iterable, first and last are set to defaultvalue. For an iterable with just one element, first and last will both refer to that one element. For any other finite iterable, first will have the first element, last the very last.

like image 109
Martijn Pieters Avatar answered Nov 06 '22 01:11

Martijn Pieters


Based on my answer to the linked question:

Probably worth using __reversed__ if it is available. If you are providing the iterator, and there is a sensible way to implement __reversed__ (ie without iterating from end to end) you should do it

first = last = next(my_iter)
if hasattr(my_iter,'__reversed__'):
    last = next(reversed(my_iter))
else:
    for last in my_iter:
        pass
like image 20
John La Rooy Avatar answered Nov 06 '22 02:11

John La Rooy