3

In python,

how can i do something like that

a = ["pera", "uva", "maca", "saladamista"]
b = a.reverse()

but without assign the reverse list to a?

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
Pabluez
  • 2,653
  • 3
  • 19
  • 29
  • 1
    That snippet doesn't "assign the reverse list to a", it calls the list's `reverse` method which mutates the very same list object `a` refers to. [Confusing variables and objects](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) is easy but harmful. –  Dec 02 '11 at 16:40
  • 1
    no, because with the [:], b is a **copy** of a, not a **reference** to it, so you call b's reverse, after making it's value the same as a. – bigblind Dec 02 '11 at 16:42
  • 1
    @FrederikCreemers: I wasn't commenting on sinan's suggestions (which is not a comment but an answer by the way) but on OP's confused statement. –  Dec 02 '11 at 16:45

2 Answers2

7

First copy the list, then reverse the copy:

a = ["pera", "uva", "maca", "saladamista"]
b = a[:]
b.reverse()

or use the "Martian smiley":

b = a[::-1]

Edit: In case someone is interested in timings, here they are:

In [1]: a = range(100000)

In [2]: %timeit b = a[:]; b.reverse()
1000 loops, best of 3: 436 us per loop

In [3]: %timeit b = a[::-1]          
1000 loops, best of 3: 414 us per loop

In [4]: %timeit b = list(reversed(a))
1000 loops, best of 3: 823 us per loop
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • how does this "martian smiley" works? Do you have a link for that concept? thank you for the answer. I was looking to the simple way to do that.. the way python programmers prefer and the most readable. – Pabluez Dec 02 '11 at 16:59
  • 1
    @Pabluez: Have a look at [this answer by Alex Martelli](http://stackoverflow.com/questions/3705670/best-way-to-create-a-reversed-list-in-python). – Sven Marnach Dec 02 '11 at 17:03
6

Try this instead:

b = list(reversed(a))
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635