Reputation: 11169
Is this the best syntax that I can get to iterate over a sequence of numbers:
for num in range(1000).__reversed__():
print i
How good is reversed(range(1000))? I think that it will generate a list and then iterate over the individual elements. Am I right?
Upvotes: 2
Views: 71
Reputation: 29416
for num in xrange(999, -1, -1):
print i
Edit: assuming you use python3
, here is the slightly changed piece of code:
for num in range(999, -1, -1):
print(i)
Upvotes: 2
Reputation: 12496
You can specify the step value as a negative number to iterate in reverse.
for num in range(999, -1, -1):
print(num)
Upvotes: 0
Reputation: 82440
Well, you have a couple of options. Firstly, you can use reversed
, and thats one good way to do it. You can also use range(999, -1, -1)
, (xrange
if you're in python 2) to do it.
You can also do this, if you have a list some_list[::-1]
.
Upvotes: 0