Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading