Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Sequences Sequence Iteration Iterating with Ranges

mohan Abdul
PLUS
mohan Abdul
Courses Plus Student 1,453 Points

how comes this code only iterates 9 times?

how comes this code only iterates 9 times?

for i in range(1, 10, 1):
    print(i)
Thanaphon Chavengsaksongkram
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Thanaphon Chavengsaksongkram
Front End Web Development Techdegree Graduate 13,464 Points

range function generates a list from start to end -1. The default start is 0.

range(5) = [0,1,2,3,4] <--- You get 5 iterations since it start from 0 range(1,5) = [1,2,3,4] <--- You only get 4 iterations since it start from 1

mohan Abdul
mohan Abdul
Courses Plus Student 1,453 Points

Thanaphon Chavengsaksongkram, so regardless of the start number, the iteration always starts at 0?

mohan Abdul
mohan Abdul
Courses Plus Student 1,453 Points

Thanaphon Chavengsaksongkram, Thanks for the speedy reply, unfortunately it wont let me give positive mark or best answer. Are you sure you are replying in the answer box?

1 Answer

Steven Parker
Steven Parker
229,644 Points

The "stop" argument of a range is not the last value, but the limit value. 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. Notice that comparison is less than (not "less than or equal").

For more details, see the chapter on ranges in the Python documentation.