Python: Why does this array get 'gridwidth' amount of indices?

Viewed 32
for i in range(0, gridwidth):
        row.append(random.randint(0, 1))

Since array indexing starts at 0, I assumed that the row array would have gridwidth + 1 indices, since it would count every integer up to and including gridwidth, but also 0. However, after checking the array, it contains only gridwidth amount of indices. While it doesn't hinder my code, I'm curious as to why this is happening.

4 Answers

While it doesn't hinder my code, I'm curious as to why this is happening.

Well, you made the following assumption:

since it would count every integer up to and including gridwidth, but also 0.

Did you try testing that assumption?

for i in range(0, gridwidth):
    print(i)

Notice that the value of gridwidth is not printed.

Or you could have tried reading the documentation:

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return an object that produces a sequence of integers from start (inclusive) |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).

The reason it happens this way is because that is how range is defined to work.

The motivation for defining range that way is because that's what programmers are accustomed to - because in older languages that make you index into arrays in their loops (instead of just getting the items directly) it's easier to avoid logical errors that way.

If you are really curious, try this:

print(len(range(0, gridwidth)))

Then, have a look at range() documentation,

the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop

The range(0, gridwidth) (range is a class of immutable iterable objects) will return a sequence having numbers from 0 to (gridwidth - 1).

for i in range(0, 5):
    print(i)

Outputs:

0
1
2
3
4

your for loop will iterate gridwidth times so your row will have gridwidth elements appended, also you may pay attention to the built-in class range who is giving you the number of iterations for your for loop, the range will give you numbers between 0 and gridwidth - 1

also, range(0, gridwidth) it is the same with range(gridwidth) the start point for range is by default 0

if you want to achieve gridwidth + 1 elements appended to your row you may use:

for i in range(gridwidth + 1):
        row.append(random.randint(0, 1))

That is because range function is closed on left side and open on right side. What that means is it will include 0 but not gridwidth. The mathematical notation is [0, gridwidth). So your iteration is from 0 togridwidth-1making array containgridwidth` elements.

Related