Python - Statement range

Introduction

range function is a general tool for looping.

It's used most often to generate indexes in a for loop.

Demo

print( list(range(5)), list(range(2, 5)), list(range(0, 10, 2)) )

Result

With one argument, range generates a list of integers from zero up to but not including the argument's value.

If you pass in two arguments, the first is taken as the lower bound.

An optional third argument can give a step. Python adds the step to each successive integer in the result.

The step defaults to 1.

Ranges can also be non-positive and non-ascending:

Demo

print( list(range(-5, 5)) )
print( list(range(5, -5, -1)) )

Result

Related Topics