Reversing Iteration: Going through a list forwards and backwards in Python

in #python6 years ago

gif.gif

One of the things Python lacks is the in-built ability to go back one item when iterating through a list.

Yes, you can reverse the whole list, or work from the end, but if you are in the middle of the list you can not just skip back one item. There is no undo.

Fortunately, you CAN iterate via the index number of the array, but it means you need a little extra in your code to make navigating the list simple.

Image Viewer with forwards/ backward navigation

You recall my imageviewer needs to be able to skip through images.

In this enhancement we make the left cursor go back, every other interaction continues to go forward through the list.

Global variables in Python

This is NOT a purist solution.

If you try to decrement the index within a function you are going to get an error saying

UnboundLocalError: local variable 'index' referenced before assignment

So we use the global statement to tell Python to not treat it as a new variable:

def key_press(event):
    global index
    if event.keysym != 'Left':
        event_action(event)
    else:
        print("LEFT!")
        index -= 2
        event_action(event)

If the key is anything but left cursor we go ahead as usual, otherwise we decrement index.

We decrement by 2 simply because of how we are incrementing in the display code loop and we want to get ahead of the picture we are going to display.

    if index < (len(files)-1):
        index += 1

Where before we did a for each, we now need to use the index:

# for each file, display the picture
while True:
    file = files[index]

Easy!


Coin Marketplace

STEEM 0.20
TRX 0.16
JST 0.030
BTC 65910.66
ETH 2696.65
USDT 1.00
SBD 2.88