Python Forum

Full Version: Indexing problem while iterating list and subtracting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have two lists of equal length, and I want to iterate through both lists while performing subtractions.

# Consider the lists
a = [x, y, z, a, b] # All ints
b = [x2, y2, z2, a2, b2] # All ints

# Expected result would be x = [x - x2, y - y2... b - b2]

I tried this with the following but got the error IndexError: list index out of range. Any ideas what I'm getting wrong?
machine_levels = [machine_levels[i] - active_recipe[i] for i in machine_levels]
Hard to say what's wrong when we can't see what machine_levels is originally.

However, you could do this and avoid the problem instead:

machine_levels = [x - y for x, y in zip(a,b)]
I am making an assumption that you want to do something like this:
# Consider the lists
a = [1, 2, 3, 4, 5] # All ints
b = [5, 4, 3, 2, 1] # All ints
 
a = [a[i] - b[i] for i in a]
print(a)
The problem is "for i in a" is going to return values from a, not an index. In my example this almost worked until it ran into "5" which is not a valid index. Lucky for me (and you) that a (or in your case machine_levels) did not contain only values that are also valid indices. Those results would be a real head scratcher.

Zip is a good choice for something like this, or you could use the old standby of "for i in range(len(machine_levels))"