Access last element after iteration
dn
PythonList at DancesWithMice.info
Tue Jul 7 17:28:13 EDT 2020
On 8/07/20 12:45 AM, Chris Angelico wrote:
> 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.
It wasn't clear if the OP was interested in the value of the pertinent
index or that of the indexed element from the iterable/sequence.
However, the techniques apply - adding enumerate() if the source is a
collection (for example).
Am impressed to see a constructive use of the else: clause! It is a most
pythonic construction used in that mode.
OTOH/IMHO, one of the harder philosophical lessons to learn, is that (in
Python at least) an exception is not necessarily an error - as in
'catastrophe'! Accordingly, there are many examples where 'success' in
such a search-pattern might be terminated with raise.
The 'calling routine'/outer-block would then be able to utilise a
try...except...else...finally structure - arguably both 'richer' and
better-understood by 'the average pythonista' than for...else/while...else
(per previous discussions 'here')
Your thoughts?
Apologies to OP, if am 'hi-jacking' original post.
--
Regards =dn
More information about the Python-list
mailing list