How to make a reverse for loop in python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 20 20:12:03 EDT 2008


On Sat, 20 Sep 2008 16:22:31 -0700, Alex Snast wrote:

> That's a lot of responses guys. Thanks a lot i think i got it. Another
> question, are there any pointers in python (or iterators) for when i use
> a data structure that doesn't support random access?


That surely depends on the data structure. 

Assume it supports sequential access: data[0], data[1], data[2], etc in 
that order without skipping or going backwards. Then you can simply do 
this:

for item in data:
    process(item)

which is the equivalent of this:

try:
    i = 0
    while True:
        process(data[i])
        i += 1
except IndexError:
    pass  # we're done


The data structure might not support sequential indexing, but still 
support sequential access:

for item in iter(data):
    process(item)


If the data structure is some sort of binary tree, then you would use a 
standard tree-walking algorithm, something like this:

def prefix_traversal(node):
    process(node.info)
    prefix_traversal(node.left)
    prefix_traversal(node.right)


and similarly for infix and postfix. (Although the specific names 'left', 
'right', 'info' are arbitrary.)


If you don't have any specific knowledge of how to iterate over the data 
structure, then try reading the docs *wink*.


-- 
Steven



More information about the Python-list mailing list