Best way to check that you are at the beginning (the end) of an iterable?

Terry Reedy tjreedy at udel.edu
Thu Sep 8 03:08:11 CEST 2011


On 9/7/2011 8:24 PM, Steven D'Aprano wrote:

> I don't think this question is meaningful. There are basically two
> fundamental types of iterables, sequences and iterators.

And non-sequence iterables like set and dict.

> Sequences have random access and a length, so if the "start" and "end" of
> the sequence is important to you, just use indexing:
>
> beginning = sequence[0]
> end = sequence[-1]
> for i, x in enumerate(sequence):
>      if i == 0: print("at the beginning")
>      elif i == len(sequence)-1: print("at the end")
>      print(x)

And finite non-sequences can be turned into sequences with list(iterable).

-- 
Terry Jan Reedy




More information about the Python-list mailing list