How to detect the last element in a for loop
Tom Verbeure
tom.verbeure at verizon.no.sp.am.net
Sat Jul 27 17:33:27 EDT 2002
>>
>> Hello All,
>>
>> I often have the case where I need to loop through a bunch of elements,
>> but do something special on for the last line of code.
>
> That's not what you're doing below:
>
>> Currently, I can solve it this way:
>>
>> first = 1
>> for port in self.portDefsList:
>> if first == 0:
>> string += ", "
>> else:
>> first = 0
>> string += str(port)
>> pass
>
> Here, you're doing something special (avoiding the += ", ") the FIRST
> time. The pass is unconditional and adds absolutely nothing -- just
> take it away.
Duh. I copied the wrong piece of code. :-]
> Anyway, this specific need is met to perfection by:
> string += ", ".join([ str(port) for port in self.portDefsList ])
Interesting.
My focus wasn't really on joining strings, but I didn't know this either.
> This does assume that you have a sequence, not just an iterator, and can
> thus slice off the first or last items easily. It's trickier but
> not difficult to do special-on-first on an iterator:
>
> processfirst(iterator.next())
> for item in iterator:
> processnormal(item)
>
> the .next call returns and "consumes" the first item, so the following
> for starts from the second one, and all is sweetness and light.
I am not familiar with iterators as objects in Python. I understand that
for a in myList:
...
will result in an implicit iterator on myList. How would you create an
explicit iterator object of myList?
> Detecting the LAST item for special processing is trickier still if
> what you DO have is an iterator. You basically have to "stagger"
> the output, e.g.:
>
> saved = iterator.next()
> for item in iterator:
> processnormal(saved)
> saved = item
> processlast(saved)
Given that you have an explicit iterator, wouldn't it be trivial to add an
'end()' method to this iterator to indicate the end of the sequence (just
like C++ iterators) ?
This would result in:
for item in iterator:
if iterator.next().end():
do_something_special
do_something_for_all
Thanks,
Tom
More information about the Python-list
mailing list