Python Forum
Indexing problem while iterating list and subtracting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Indexing problem while iterating list and subtracting
#1
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]
Reply
#2
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)]
Reply
#3
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))"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with subtracting values using SQLite & Python Extra 10 3,419 May-10-2022, 08:36 AM
Last Post: ibreeden
  Problem with "Number List" problem on HackerRank Pnerd 5 2,126 Apr-12-2022, 12:25 AM
Last Post: Pnerd
  Subtracting datetimes [index] Mark17 2 2,483 Aug-21-2021, 12:11 AM
Last Post: Larz60+
  Delete list while iterating shantanu97 1 1,898 Jun-06-2021, 11:59 AM
Last Post: Yoriz
  slicing and indexing a list example leodavinci1990 4 2,362 Oct-12-2020, 06:39 AM
Last Post: bowlofred
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,307 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  python3: iterating through list not working wardancer84 3 2,368 Jul-08-2020, 04:30 PM
Last Post: DPaul
  TypeError indexing a range of elements directly on the list JFerreira 2 2,216 Mar-30-2020, 04:22 PM
Last Post: bowlofred
  How to change 0 based indexing to 1 based indexing in python..?? Ruthra 2 4,344 Jan-22-2020, 05:13 PM
Last Post: Ruthra
  iterating a span of a list Skaperen 5 3,069 Dec-29-2019, 08:15 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020