-1

How to reverse a list in python? I tried:

a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]
print a
a = reversed(a)
print a

But I get a <listreverseiterator object at 0x7fe38c0c> when I print a the 2nd time.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
michael
  • 106,540
  • 116
  • 246
  • 346

3 Answers3

2

use a[::-1]

its the pythonic way of doing it.

Hrishi
  • 7,110
  • 5
  • 27
  • 26
-1
print a[::-1]

you could use this

Vaibhav Aggarwal
  • 1,381
  • 2
  • 19
  • 30
-1

Python gives you a very easy way to play around with lists

Python 2.7.3 (default, Apr 24 2013, 14:19:54)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ["abc", "def", "ijk", "lmn", "opq", "rst", "xyz"]
>>> a
['abc', 'def', 'ijk', 'lmn', 'opq', 'rst', 'xyz']
>>> a[::-1]
['xyz', 'rst', 'opq', 'lmn', 'ijk', 'def', 'abc']
>>>

And you can read up more on slincing in this very helpful SO post: Explain Python's slice notation

Community
  • 1
  • 1
Tymoteusz Paul
  • 2,732
  • 17
  • 20