I'm new to python and am wondering about counting down values of an array in reverse:
a = [1, 2, 3, 4]
def countdown_reversed(lists):
for x in reversed(lists):
print(x) # why is it x and not lists[x]?
countdown_reversed(list)
I'm new to python and am wondering about counting down values of an array in reverse:
a = [1, 2, 3, 4]
def countdown_reversed(lists):
for x in reversed(lists):
print(x) # why is it x and not lists[x]?
countdown_reversed(list)
From Python documentation(https://docs.python.org/2/tutorial/controlflow.html)
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
If you need the index of the current list element you can use snippet from the same url:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]
With result:
0 Mary
1 had
2 a
3 little
4 lamb
Your using a for
loop that is based on elements in the collection not indices, for example:
chars = ['a', 'b', 't']
for char in chars:
print char
for i in range(len(chars)):
print chars[i]
When you use
for a in b
python returns each of the items in b one at a time rather than the index.
If you need the index then you could use the range function with -1 as the 3rd optional variable to countdown by 1 each time. Take care though because in python range will go from the start value up to but not including the last, hence why there are -1's everywhere in this code
list = [1, 2, 3, 4]
def countdown_reversed(lists):
for x in range(len(lists)-1,-1,-1):
print(x) # will return index
print(lists[x]) # will return value
countdown_reversed(list)