-1

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)
devdropper87
  • 4,025
  • 11
  • 44
  • 70
  • you are reversing the list and printing each element what do you expect? – Padraic Cunningham Feb 01 '15 at 17:18
  • 2
    Don't use `list` it's a built-in. – Malik Brahimi Feb 01 '15 at 17:19
  • you can reverse lst like this `lst = lst[::-1]` – Gadol21 Feb 01 '15 at 17:22
  • `for x in somelist` gives x as an *index* **in Javascript**, but as an *element* **in Python** -- this semantic difference may explain the confusion in the comment (if you're coming to Py from JS). Also, please edit the Q's subject as it has nothing to do with counting, and to fix the broken indentation (the two lines in the function's body need to go 4 spaces rightwards). – Alex Martelli Feb 01 '15 at 17:28
  • yep I am coming from JS! ok on the indentation and thanks. what's the best subject? – devdropper87 Feb 02 '15 at 17:48

3 Answers3

1

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
luantkow
  • 2,809
  • 20
  • 14
0

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]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

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)
wnbates
  • 743
  • 7
  • 16