pythonloopsiteration

Loop that also accesses previous and next values


How can I iterate over a list of objects, accessing the previous, current, and next items? Like this C/C++ code, 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];
    }
}

Solution

  • This should do the trick.

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

    Here's the docs on the enumerate function.