Python: Generate List: range

By Xah Lee. Date: . Last updated: .

range is used for generating a list of integers.

range(n)
Represent a sequence of integers from 0 to n, not including n.

n must be a integer.

range(start, stop)
Represent a sequence of integers from start to stop, not including stop.

All arguments must be integers.

range(start, stop, step)
Represent a sequence of integers from start to stop, not including stop, in steps of step

All arguments must be integers.

Warning: range is not a function, does not return a list. It is a Immutable Sequence Type. Meaning, it does not actually generate items until its used.

# demo that range is not a function.
# it does not eval to list till used.
# range is technically a Immutable Sequence Type

print(range(1, 4))
# this prints literally range(1, 4) as is. not printing [1,2,3]

print(type(range(1, 4)))  # <class 'range'>

print(type([1, 2, 3]))  # <class 'list'>

Convert range to list

list(range(args))

xx = range(1, 4)
print((xx == [1, 2, 3]) == False)

# force range into a list
yy = list(xx)

print(yy == [1, 2, 3])

Python Data Structure