fbpx

The Range Function

The range() function allows us to create a list of values from a given starting value (inclusive), and ending value (exclusive). For example, to create a list of all the values from 1 to 10, I could use the following code:

				
					# create a list from 1 (inclusive) to 11 (exclusive)
nums = range(1, 11)
				
			

We could then print out the numbers in that range by using the following for loop:

				
					nums = range(1, 11)

# print out each number 1 to 10 on its own line:
for n in nums:
    print(n)
				
			

It is probably even more efficient to combine the creation of the list with the iteration of the list, by doing the following:

				
					# print out each number 1 to 10 on its own line:
for n in range(1, 11):
    print(n)
				
			

The range() function also allows us to input a third optional parameter to specify the step which we change the value by with each iteration. By default, this is 1, but if we wanted to say count by 5’s from 0 to 30, we could do the following:

				
					for i in range(0, 31, 5):
    print(i)
    
# output:
# 0
# 5
# 10
# 15
# 20
# 25
# 30
				
			

We could also use a negative value for the step to count down:

				
					for i in range(5, 0, -1):
    print(i)
print("Liftoff!")

# output:
# 5
# 4
# 3
# 2
# 1
# Liftoff!
				
			

Here is an alternate way to print out the names in a list using the range() function, this time printing out their index as well as we go:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

for i in range(0, len(students)):
    print("Student", i, "is", students[i])
    
# Output:
# Student 0 is Luke
# Student 1 is Leia
# Student 2 is Han
# Student 3 is Chewie
# Student 4 is Lando
				
			

In conclusion, the range() function helps us more efficiently iterate through lists and ranges of values, as evidenced in the examples above.

Replit Practice

Loading...