-1

I want to make a for loop in python to go over a list. However, I would like to have it going through the list in the opposite direction. For example

  foo = [1a,2b,3c,4d]
  for number in foo:
      print number

the result of this code should be: 4d 3c 2b 1a and not 1a 2b 3c 4d.

Any elegant way to do this? Or is it best to reorder the initial list itself?

Many thanks for your advice

user3184086
  • 711
  • 1
  • 9
  • 16

3 Answers3

7
for number in reversed(foo):
    print number

This has the advantage of not creating a reversed copy of foo; reversed returns a reverse iterator over the list. Also, it works with anything that supports len and indexing with integers.

user2357112
  • 260,549
  • 28
  • 431
  • 505
4
foo = [1a,2b,3c,4d]
for number in foo[::-1]:
    print number
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
2

Just reverse it with slicing notation

print foo[::-1]

Output

['4d', '3c', '2b', '1a']

Or use reversed function,

print "\n".join(reversed(foo))

Output

4d
3c
2b
1a
thefourtheye
  • 233,700
  • 52
  • 457
  • 497