The range() function in Python is a built-in way to generate a sequence of numbers. You often see it used in
loops (like for) or anytime you need a sequence of integers without storing them in a list up front.
Basic Syntax
range(start, stop, step)
start → The number to begin at (default =
0).
stop → The number to end at (this number is
excluded).
step → The increment (default = 1). Can be negative for counting backwards.
Examples
Simplest usage (only stop):
for i in range(5):
print(i)
Output:
0
1
2
3
4
(It starts at 0, ends before 5.)
With start and stop:
for i in range(2, 7):
print(i)
Output:
2
3
4
5
6
With step:
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Counting backwards:
for i in range(10, 0, -2):
print(i)
Output:
10
8
6
4
2
Key Details
range()does not create a list; it creates a special object (a
range object) that generates numbers on demand (memory efficient).
If you need the actual list, wrap it with list():
list(range(5)) # [0, 1, 2, 3, 4]
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
range()function in Python is a built-in way to generate a sequence of numbers. You often see it used in loops (likefor) or anytime you need a sequence of integers without storing them in a list up front.Basic Syntax
start→ The number to begin at (default =0).stop→ The number to end at (this number is excluded).step→ The increment (default =1). Can be negative for counting backwards.Examples
Simplest usage (only
stop):Output:
(It starts at
0, ends before5.)With
startandstop:Output:
With
step:Output:
Counting backwards:
Output:
Key Details
range()does not create a list; it creates a special object (a range object) that generates numbers on demand (memory efficient).If you need the actual list, wrap it with
list():