dir01 dir01 - 7 months ago 13
Python Question

Python - Previous and next values inside a loop

How can I do thing like this in python?

foo = somevalue
previous = next = 0

for (i=1; i<objects.length(); i++) {
if (objects[i]==foo){
previous = objects[i-1]
next = objects[i+1]
}
}

Answer

This should do the trick.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
    if obj == foo:
        if index > 0:
            previous = objects[index - 1]
        if index < (l - 1):
            next_ = objects[index + 1]

Here's the docs on the enumerate function.