-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
  • 963,270
  • 265
  • 3,804
  • 3,187
michael
  • 99,904
  • 114
  • 238
  • 340

3 Answers3

2

use a[::-1]

its the pythonic way of doing it.

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

you could use this

Vaibhav Aggarwal
  • 1,333
  • 2
  • 17
  • 28
-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,648
  • 16
  • 19