Access last element after iteration

Chris Angelico rosuav at gmail.com
Tue Jul 7 08:45:10 EDT 2020


On Tue, Jul 7, 2020 at 10:28 PM Frank Millman <frank at chagford.com> wrote:
>
> Hi all
>
> After iterating over a sequence, the final element is still accessible.
> In this case, the variable 'i' still references the integer 4.
>

Yes, it's guaranteed. It isn't often useful; but the variant where
there's a "break" in the loop most certainly is. If you hit the break,
the iteration variable will still have whatever it had at the end.

This is a great use of 'else' (arguably the primary use of it). You do
something like:

for thing in iterable:
    if want(thing): break
else:
    thing = None

If the iterable is empty, you go to the else. If you don't find the
thing you want, you go to the else. But if you find it and break,
thing has the thing you wanted.

ChrisA


More information about the Python-list mailing list