Python Range

The python range function is useful for iterating through a list of integers.

The full syntax is

range(start, stop, step)
Python using Laptop

The following example shows

  • Just specifying a stop, where start defaults to 0 and increment to 1
  • Specifying a stop and start, with increment defaulting to 1
  • Specify a stop, start and increment, to go through the even numbers only.
allSizes1 = range(10)
allSizes2 = range(1,10)
evenNumbers = range(2,10, 2)

for i in allSizes1:
  print("Size", i)

print("-----------")

for i in allSizes2:
  print("Size", i)

print("-----------")

for i in evenNumbers:
  print("Number",i)

When we run it, we get the following

> python range.py
Size 0
Size 1
Size 2
Size 3
Size 4
Size 5
Size 6
Size 7
Size 8
Size 9
-----------
Size 1
Size 2
Size 3
Size 4
Size 5
Size 6
Size 7
Size 8
Size 9
-----------
Number 2
Number 4
Number 6