range() function¶Let's take a look at the range() function
range(1,10)
A range is a new type - it's a sequence like a list
type(range(1,10))
range(start,end) creates a sequence of numbers that begin with start and ending just before end
list(range(1,10))
range()¶The range() function is often used with for loops to create counter-controlled loops where you don't have to explicitly manage the counter.
for i in range(1,10):
print("This is iteration",i)
range()¶The range() function can also take 1 or 3 arguments instead of just 2.
When used with 1 argument, the start is implied to be 0.
for i in range(10):
print(i)
When used with 3 arguments, the third argument tells it what to increment the counter by.
for i in range(1,10,2):
print(i)
You can even use this to count backwards.
for i in range(10,0,-1):
print(i)
print("Blast off!")
For each of the following loops, predict what will be displayed, then run it to see if you were right.
for num in range(1,5):
print(num)
for num in range(5,10):
print(num)
for num in range(0,5,2):
print(num)
for num in range(5,2,-1):
print(num)
for num in range(5):
print(num)
for num in range(9,10):
print(num)
for num in range(10,10):
print(num)
for num in range(1,10,100):
print(num)
range() and lists¶range() is often used with a for loop when you prefer to access the items using an index
For example, consider this while loop we wrote in a previous lab.
rainfall = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
counter = 0
while counter < len(rainfall):
print("Day",counter,"had",rainfall[counter],"inches of rainfall.")
counter += 1
If we want to do this with a for loop, we lose the ability to print the day number. We would have to explicity keep track of a counter again - so then we might as well just use a while loop.
rainfall = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
for amount in rainfall:
print("Day ? had",amount,"inches of rainfall.")
Instead, we could make a range() with all the indices of our list by using the len() of the list:
list( range(len(rainfall)) )
for counter in range(len(rainfall)):
print("Day",counter,"had",rainfall[counter],"inches of rainfall.")
When using a for loop to iterate through a list, always determine which you are doing:
range()[] notation for your list, just use the loop variablerange(len(name_of_list))[loop_counter] to access items in the listrainfall = [0.0, 0.3, 0.71, 0.0, 0.32, 1.1, 0.4]
for amount in rainfall:
print("Day ? had",amount,"inches of rainfall.")
for counter in range(len(rainfall)):
print("Day",counter,"had",rainfall[counter],"inches of rainfall.")
It's really easy to mix these up - be ready to look for this if your loops are working.
for x in rainfall:
print(rainfall[x],"inches of rainfall.")