[Tutor] for loop issue

Kent Johnson kent37 at tds.net
Fri Oct 9 14:02:28 CEST 2009


On Fri, Oct 9, 2009 at 3:54 AM, Stefan Lesicnik <stefan at lsd.co.za> wrote:
> Hi,
>
> This feels like a strange issue, so i hope I formulate this so its
> understandable.
>
> I have some objects. Each object has associated values. I am looping
> through these objects, working with a value and printing out the
> value.
> The issue in this case is that i need to check if the one value
> superseeds the other, and in that case, not print it out. I think the
> problem is that when you are in the loop, you dont know about the
> other object that you havent processed yet, and when you are
> processing that object, you dont know about the previous one?  (not
> 100% sure if this assumption is correct)

You can easily keep track of the previous item by assigning it to a
variable. For example this shows just the increasing elements of a
sequence:

In [22]: items = [0, 1, 3, 2, 8, 5, 9 ]

In [23]: last = None

In [24]: for item in items:
   ....:     if last is None or item > last:
   ....:         print item
   ....:     last = item

0
1
3
8
9


More information about the Tutor mailing list