laika222
1/3/2019 - 11:32 PM

Range

# Range is used to create an immutable sequence of numbers between the start integer and the stop integer.
# The format is range(start, stop, step). The stop and step arguments are optional. If you supply only a single
# argument, the format will be interpreted as range(stop).

# To create a range with a certain number of integers, enter a single argument. This will be interpreted as
# range(stop), with 0 being the default for the start and 1 being the default for step. So it's the same
# as putting in range(0, 10, 1).
print(list(range(10))) # result is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Supplying two arguments are interpreted as the start number and the stop number.
# The example below is the same as writing range(1, 20, 1).
print(list(range(1, 20))) # result is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

# Supplying three arguments allows you to specify the start, stop, and step.

print(list(range(1, 20, 2))) # result is [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

# You will often see range in for loops:
for iteration in range(5): # while this is True, do what follows the colon on next line (iteration is variable with a range of 5 (it'll go through the loop 5 times))
    print('This is iteration number (' + str(iteration) + ')') # print 'This is iteration number' plus the value of iteration during this iteration of the loop
    
# Results:
  # This is iteration number (0)
  # This is iteration number (1)
  # This is iteration number (2)
  # This is iteration number (3)
  # This is iteration number (4)
  
# HOW IT WORKS

# The range function will create the list of numbers and the range function then be substituted out for the list.
# Therefore, these two loops are exactly the same:
for iteration in range(5): # using range
    print('This is iteration number (' + str(iteration) + ')')
    
for iteration in [0, 1, 2, 3, 4]: # how range(5) is actually interpreted
    print('This is iteration number (' + str(iteration) + ')')