15/18 Range vs not


#1

Hello,

I’m not stuck on this one. However I am curious.

I understand that the following code works but I’m not understand why .

I’m having a hard time following each step of this code and what exactly is happening with range().

n = [3, 5, 7]

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

Additionally is there a situation where range() would be more suitable vs using code like this?

n = [3, 5, 7]

def total(numbers):
  result = 0
  for x in numbers:
    result += x
  return result

I find the second example very easy to follow through exactly what is happening. But not so much with the use of range().

Hopefully someone can simplify this for me.

Thanks


#2

range() produces a list:

print range(3) # [0, 1, 2]

by using range like you did, the list produces by range perfectly gives you indexes, this is useful when you need to modify every element in the list for example. Given that is not the case, i would go for the second code.


#3

I see. So basically what is happening in my first code example is range produces a new list the length of the list I provided? Then I’m iterating over that number of indexes on the ‘numbers’ list?

Am I understanding this correctly?


#4

not how i would put it, range produces a list you are looping over. The values from range list happen to match the indexes of your numbers list


#5

Thanks,

I think I understand now!


#6

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