15/18 - just curious, why doesnt "for i in numbers" iterate through the list?


I feel like the " for i in numbers:" part should be iterating through each element in the list. What is actually happening?

Why do I need to have it as this?

def total(numbers):
  result = 0
  for i in range(len(numbers)):
    result += numbers[i]
  return result

Instead of this?

def total(numbers):
  result = 0
  for i in numbers:
    result += numbers[i]
  return result

To be more specific, the latter code gives the error:

IndexError: list index out of range


it does, but it gets the values from the list so you can add i directly to result.

using range() gives you indexes, in which case you need to use the square brackets to get the value from the list.

without range, you get the values directly, which might be higher then the indexes of the list, as such, your code throws an error when trying to use the values from the list as indexes


That’s just the thing. It does. But you’re using them like indexes

(If you add print statements in your code you can print out things as it happens, such as the value of i)


You are a genius and my mind has been blown. Thanks so much.


Thanks! I’ll keep this advice in mind so I can debug my code more easily.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.