range()
A for loop walks through the items of a list. But sometimes you don't have a list — you just want to repeat something a fixed number of times, or count through a span of numbers. That's what range() is for.
range(stop) — count from 0
range(n) produces the numbers from 0 up to but not including n:
Output:
That's five numbers (0, 1, 2, 3, 4) — 5 itself is not included. This "up to but not including" rule is the same idea as list indexing starting at 0.
range(start, stop) — count from anywhere
Give it two numbers and it counts from start up to (but not including) stop:
Output:
Now you get 1 through 5 — useful when you want to count starting at 1.
Repeat something N times
When you don't care about the number itself, just use range() to repeat:
Output:
Looping over a list by index
range(len(my_list)) gives you every valid index of a list — handy when you need the position, not just the value:
Output:
Key takeaways
range(n)counts from0up to but not includingnrange(start, stop)counts fromstartup to but not includingstop- Use
for i in range(n):to repeat code a fixed number of times range(len(list))produces every valid index of a list
No comments yet. Add the first comment to start the discussion.