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

Time:09-28

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')

CodePudding user response:

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')
  • Related