-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
  • 691
  • 1
  • 9
  • 16

3 Answers3

6
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
  • 235,058
  • 25
  • 372
  • 444
4
foo = [1a,2b,3c,4d]
for number in foo[::-1]:
    print number
CT Zhu
  • 49,083
  • 16
  • 110
  • 125
1

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
  • 221,210
  • 51
  • 432
  • 478