Screen Link: https://app.dataquest.io/m/1009/lists-and-for-loops-practice-problems/11/understanding-code-5
My Code:
for i in range(10):
print(i)
i = 11
Replace this line with your code
I expected 10 to be part of the result:
code runs and stops at 9:
Replace this line with the output/error
Why is this so?: -->
1 Like
@andreseremba
Range was designed to exclude the stop
value.
Kindly check out the range documentation
3 Likes
Hi @andreseremba:
Remember that python is zero-indexed, meaning that the first iteration of the loop starts the iterator i
at 0
(unless it is explicitly specified). Since the argument specified in the range argument is 10
(the loop will run for 10
iterations–0
to 9
inclusive) and it is specified in the documentation that the stop
value is not included, i
will be 9
for the last iteration of the loop, since i
is incremented by 1
for each iteration of the loop.
The for loop takes the following format:
for i in range(start, stop, step):
The loop can be re-written as follows:
for i in range(0, 10):
The default value of start
is 0
if it is not specified (providing only 1 argument to the range()
function makes python treat it as the stop
value).
first iteration of the loop starts the iterator i
at 0
(unless it is explicitly specified)
To initialise the start
value to 1
for example, simply specify it as follows:
for i in range(1, 10):
# ^ specify start value before the comma
Hope this helps!
3 Likes
Very Simplified,
Thank you so much.
2 Likes
If it helped you do you mind marking my reply as the solution to benefit others? Thanks!
2 Likes
I have a question. Why doesn’t (i = 11) force the code to run out of for loop immediately. Even when I tried i = 8, there wasn’t any change in the output and it prints 0 -> 9.
1 Like
Hi @srivastava.anurag008 good question. The iterator i
depends on the argument(s) specified in the range()
function. Thus, trying to assign/reassign a value to the iterator before or after the loop declaration does not work. range()
is of immutable type as described in this article meaning you cannot change the value in which the iterator goes over by attempting to change the iterator value.
On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range .
#does not execute 8 times
i = 8
for i in range(0, 10):
...
#also does not execute 8 times
for i in range(0, 10):
...
i = 8
Here is another article about iterators that you may also find useful in cementing your understanding.
Hope this clarifies.
6 Likes
Thanks @masterryan.prof
Great explanation.
1 Like