Level 1
0 / 100 XP

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:

Python
for i in range(5): print(i)

Output:

Text
0 1 2 3 4

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:

Python
for i in range(1, 6): print(i)

Output:

Text
1 2 3 4 5

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:

Python
for i in range(3): print("Hello")

Output:

Text
Hello Hello Hello

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:

Python
fruits = ["apple", "banana", "cherry"] for i in range(len(fruits)): print(i, fruits[i])

Output:

Text
0 apple 1 banana 2 cherry

Key takeaways

  • range(n) counts from 0 up to but not including n
  • range(start, stop) counts from start up to but not including stop
  • Use for i in range(n): to repeat code a fixed number of times
  • range(len(list)) produces every valid index of a list