For-statement to iterate through items in a list for an if-statement

Question:

Apologies for the basic question, I’m new to Python & struggling to find an answer.

How do I execute the below if-statement for each item in the list loaded_route?

i.e. check the first loaded_route value, update location, then check the next value, update location etc.

My current for-loop compares the entire list, not individual values. Thanks!

location = [1,1]
loaded_route = ['right', 'left']
route_coords = []

for route in loaded_route:
    if route == 'right':
        location[0] = (location[0] + 1)
        route_coords.append(location)
    elif route == 'left':
        location[0] = (location[0] - 1)
        route_coords.append(location)
    elif route == 'up':
        location[1] = (location[1] - 1)
        route_coords.append(location)
    elif route == 'down':
        location[1] = (location[1] + 1)
    else:
        print('failed to read loaded_route')
Asked By: RSGEO

||

Answers:

location is type list, and lists are "mutable" in Python. That means that every time you add location to route_coords, you are merely inserting a reference to location, which is allowed to keep changing.

Instead, you want to make a copy of the current location value to route_coords.

location = [1,1]
loaded_route = ['right', 'left']
route_coords = []

for route in loaded_route:
    if route == 'right':
        location[0] = (location[0] + 1)
        route_coords.append(location[:])
    elif route == 'left':
        location[0] = (location[0] - 1)
        route_coords.append(location[:])
    elif route == 'up':
        location[1] = (location[1] - 1)
        route_coords.append(location[:])
    elif route == 'down':
        location[1] = (location[1] + 1)
        route_coords.append(location[:])
    else:
        print('failed to read loaded_route')
Answered By: nofinator
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.