What do I add to result if using the range( ) method?


#1

Question

What do I add to result if using the range( ) method?

Answer

If you chose to write your loop with the range() method, you’ll need to access your list items with the current number in your range. In the code below, i holds the value of the current range value for our loop and we use that to access an index in our list.

for i in range(len(some_list)):
  print i  # This will print a number, starting at 0, going up to the list length
  result += some_list[i]  # Access the current value in our list

FAQ: Learn Python - Lists and Functions - Iterating over a list in a function
#2

Would it be correct to say that ‘for i in range(0, len(some_list):’, the i refers to each index. So you have to then use it in conjunction with the list to retrieve the value. And that the ‘for i in some_list:’ the i refers to the value itself?


#3

@danyala Yes, that’s correct. You can test it yourself by running these in your Python interpreter:

  1. example_list = ['foo', 'bar', 'baz']
    
    # len(example_list) returns the number 3
    # so range(3) would produce the same result
    for i in range(len(example_list)):
      print(i)
    
    # output:
    0
    1
    2
    
  2. example_list = ['foo', 'bar', 'baz']
    
    for i in example_list:
      print(i)
    
    # output:
    foo
    bar
    baz