I am trying to loop from 100 to 0. How do I do this in Python?
for i in range (100,0) doesn't work.
I am trying to loop from 100 to 0. How do I do this in Python?
for i in range (100,0) doesn't work.
Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).
("range" options, start, stop, step are documented here)
for i in range(100, -1, -1)
and some slightly longer (and slower) solution:
for i in reversed(range(101))
for i in range(101)[::-1]
You might want to use the reversed function in python.
Before we jump in to the code we must remember that the range
function always returns a list (or a tuple I don't know) so range(5) will return [0, 1, 2, 3, 4]. The reversed function reverses a list or a tuple so reversed(range(5)) will be [4, 3, 2, 1, 0] so your solution might be:
for i in reversed(range(100)):
print(i)
I wanted to loop through a two lists backwards at the same time so I needed the negative index. This is my solution:
a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
print(i, a[i])
Result:
-1 2
-2 5
-3 4
-4 3
-5 1
You can also create a custom reverse mechanism in python. Which can be use anywhere for looping an iterable backwards
class Reverse:
"""Iterator for looping over a sequence backwards"""
def __init__(self, seq):
self.seq = seq
self.index = len(seq)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.seq[self.index]
>>> d = [1,2,3,4,5]
>>> for i in Reverse(d):
... print(i)
...
5
4
3
2
1
Oh okay read the question wrong, I guess it's about going backward in an array? if so, I have this:
array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]
counter = 0
for loop in range(len(array)):
if loop <= len(array):
counter = -1
reverseEngineering = loop + counter
print(array[reverseEngineering])