Home » Python range() Function

Python range() Function

Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Oracle Java Certification
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests

The range() function is used to generate a sequence of numbers over time. At its most basic, it accepts an integer and returns a range object.

Syntax

range(start, stop, step)

Parameter Values

Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incremental. Default is 1

Usage examples

Here are some examples

# empty range
print(list(range(0)))

# using range(stop)
print(list(range(8)))

# using range(start, stop)
print(list(range(2, 8)))

You will see something like this

[]
[0, 1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]

generate even numbers

start = 2
stop = 10
step = 2

print(list(range(start, stop, step)))

You will see something like this

[2, 4, 6, 8]

negative example

start = 0
stop = -10
step = -2

print(list(range(start, stop, step)))

You will see something like this

[0, -2, -4, -6, -8]

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More