Indexing with modulus
Let’s generate a list of numbers from 1 to 6:
numbers = list(range(1, 7))
print(numbers)
This will print:
[1, 2, 3, 4, 5, 6]
Now let’s generate a new list of numbers that has a length of 25 and gets its numbers from the list above:
more_numbers = []
for i in range(25):
next_number = numbers[i % len(numbers)]
more_numbers.append(next_number)
print(more_numbers)
This will print:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1]
Notice that we use range(25)
to append to more_numbers
25 times. Then we use
i % len(numbers)
to get an index that will loop through the numbers
and wrap
back to the beginning as needed. Because numbers
has a length of 6, The
variable i
will take the values 0 1 2 3 4 5
and then 0 1 2 3 4 5
and so
forth.