[Tutor] How to iterate and update subseqent items in list

bob gailer bgailer at alum.rpi.edu
Thu Dec 6 20:43:31 CET 2007


ted b wrote:
> Can you suggest a good way to iterate through the
> remainder of list and update them?
>
> Ex:
> Thing1.value = 0
> Thing2.value = 1
> Thing3.value = 0
> Thing4.value = 0
>
> Things = [Thing1, Thing2, Thing3, Thing4]
>
> I want to iterate through 'Things' and if
> 'Thing.value' > 0, then I want to set all values for
> that and the subsequent 'Things' in the list to 2
>
> So that i'd end up with
>
> Thing1.value = 0
> Thing2.value = 2
> Thing3.value = 2
> Thing4.value = 2
>
>   
import itertools
for thing in itertools.dropwhile(lambda x: x.value <= 0):
    thing.value = 2

This may appear less clear at first, but understanding itertools can be 
a great benefit for addressing a multitude of problems of this nature.

I suggest looking at the itertools module documentation, and wading thru 
dropwhile to understand it. Of course I also introduced lambda here, 
which is a shortcut to defining an anonymous function.


More information about the Tutor mailing list