[Tutor] for loop issue
moron.oxy at gmail.com
Fri Oct 9 12:35:06 CEST 2009
On Fri, Oct 9, 2009 at 6:54 PM, Stefan Lesicnik <stefan at lsd.co.za> wrote:
> 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)
If I understand correctly, the items are basically in the same
collection that you're looping over. And you need to know an item
after/before the current one being iterated over.
Whether you can do this or not (or do it easily!) really depends on
what sort of sequence you are iterating over, if it's something
in-memory like a list or a tuple, it's easy, instead of iterating over
the actual items in the collection, you iterate their indexes, let's
assume your items are inside a list x:
x = ['foo', 'bar', 'baz', 'spam']
for i in xrange(0, len(x)-1):
print x[i], x[i+1]
Thus, you can muck around with x[i] (current item), and x[i+1] (next
item), and decide how you want to proceed with the loop. Note the use
of len(x) - 1 rather than just len(x) to easily prevent an IndexError
or extra special case logic.
Now, if what you're looping over is something that just follows the
iteration protocol (i.e. something you can iterate over), it may not
know or support knowing the length (look up the __len__ special method
for more info) of the items in advance, i.e. len(iterable_obj) fails.
An example of this is the file handle, which allows you to iterate
through lines in the file, but attempting to do a len(handle), e.g.:
>>> f = open('foo.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'file' has no len()
In this case, the simplest thing is to first read in the items into an
in-memory structure like a list or tuple, then use the index iteration
method above. If not all data can fit into memory, then it is time to
wrack your brains some more, I suspect you won't have to go that far
for now though :-).
Ask away if this is unclear or I got your problem description wrong.
There is more to life than increasing its speed.
-- Mahatma Gandhi
More information about the Tutor