-2

I'm sorry for the very basic question, this is a concept I can't quite grasp.

It is my understanding that the first element in a Python list has index [0]. This means that len(x)-1 should be the last element in my list x. So, if I write a loop with:

for i in range(0, len(x)-1):
  #do stuff here

This should mean that I want I to go from the first element of my list to the last one.
However, I always find written:

for i in range(0, len(x)):
  #do stuff here

Why is that? Which one is correct?

ZygD
  • 22,092
  • 39
  • 79
  • 102
  • 3
    `for i in range(len(x)):` is "unpythonic", you should use `for obj in x:`. If you need the index you should use `for i, obj in enumerate(x):` – Iain Shelvington Jan 31 '21 at 08:55
  • Check the documentation if you do not know how something works: [https://docs.python.org/3/library/stdtypes.html#typesseq-range](https://docs.python.org/3/library/stdtypes.html#typesseq-range): `class range(start, stop[, step])` _For a positive `step`, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and **`r[i] < stop`**._ So any element is strictly smaller then stop .. – Patrick Artner Jan 31 '21 at 08:59

2 Answers2

0

range(0,x) will loop up to the value of x, so < x as opposed to <= x. For example, range(0, 3) will loop over the indices 0, 1, 2.

Which means the second one is correct, as if x = [4, 5, 6, 7] (len 4) - the maximum index is 3 so you'd want to loop over the indices 0, 1, 2, 3.

James Cockbain
  • 466
  • 2
  • 4
  • 13
0

range(x, y) means to start with x and iterate till y-1 so when you use for i in range(0, len(x)-1):, it will iterate from 0 to len(x) - 2.

For example if, len(x) = 3, the statement for i in range(0, len(x)-1): will iterate from 0 to 1 so that's why we use for i in range(0, len(x)): to iterate over all the elements in the list.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35