Decrementing With range()
You can supply a negative step value to generate a list of numbers that is decreasing. If you do that, you need to make sure your stopping value is less than your starting value, or else you’ll get a list with no elements:
for i in range(10, -6, -2):
print(i)
This will start at 10
and count down by 2
until you reach -6
, or rather -4
because you don’t include -6
.
00:00
We can supply a negative step
value to generate a list of numbers that is decreasing. If we do this, then we have to make sure our stopping value is less than our starting value, or else we’ll get a list with no elements.
00:19
Think about it like this. If I ask you to count from 10 to 20, but down by 2, what numbers would you say? None. Let’s give this a try. I’ll say for i in range(10, -6, -2):
and print(i)
.
00:47
This will start at 10
and count down by 2 until we reach -6
. Or really, -4
, because we don’t include -6
.
00:59
And that’s exactly what we see! And just to show you why it’s important that the stopping value is smaller, I’m going to change -6
to a positive 20
.
01:14
And now you see that we get nothing. There’s no way to count down from 10
by 2 and get to 20
. As you can see, the range()
function lets you generate an increasing or decreasing sequence of numbers.
01:33
But what if we already have a sequence of numbers and we want to loop over them in reverse order? For that, we can use the built-in reversed()
function.
01:45
That looks like this. for i in reversed()
and I’ll pass in range(5)
. print(i)
. The range()
function will give us a list from 0
to 4
, and reversing that will allow us to iterate from the last value in the list down to the first.
02:11
You could also accomplish this by just using the range()
function without reversed()
, but we’ve included this here to show you another way you might see iteration done.
Become a Member to join the conversation.