Python for loop with a more intuitive upper bound?

for-loop, python

Solution

Yes, `for i in range(upper + 1)` or if you like, `for i in range(lower, upper + 1)` will work,

A lot of programming languages use zero-based indexing, so the non-inclusive upper bound is a common practice (this is due to memory addressing and adding an offset)

Just an example: If you had an array of size 5, `ar`, starting with index 0, your largest valid index value would be 4 (i.e., 0, 1, 2, 3, 4), but your loop construct would refer to the size of the array (5) like so:

`for i in range(5):`

or more common and better:

`for i in range(len(ar)):`

.. ensuring you only get legal index values 0 .. 4.

Problem

Sometimes it is a little confusing for me to keep in mind that the upperbound for a for loop is excluded by default. Is there any way to make it inclusive?

Original source