tags:

views:

89

answers:

2

I want to take a list [0,1,2] and turn it into [0,1,2,2,1,0]. Right now, I've got

r = list(mus)
r.reverse()
mus = mus + r

but it seems like there should be a better way. Can anyone come up with a good, pythonic one-liner?

+3  A: 

It looks like you might be in need of

mus.extend(reversed(mus))

Or if you simply need to iterate over this and not necessarily form the list, use

import itertools
for item in itertools.chain(mus, reversed(mus)):
    do_something...
Mike Graham
Ah, thanks for suggesting "extend". That was key.
Seth Johnson
+2  A: 

Just a few of the many ways to do this are:

  1. m = l + reversed(l)
  2. m = l + l[::-1]
  3. l.extend(reversed(l))
  4. l.extend(l[::-1])

The first two assign the output to a new list, and the second two update the list in place. If I was being clever, I would probably use 2 or 4, but if I wanted there to be no mistake about what I was doing, then I would opt for 1 or 3.

Hope this helps.

Edit: As pointed out in the comments, #1 doesn't work, as reversed returns an iterator. You could make it work by changing it to:

m = l + list(reversed(l))

But I can't recommend it. Go with 2 instead.

BTW, thanks for the correction and sorry for any confusion.

Aaron
Your case 1 doesn't work. (`reversed` does not return a list.)
Mike Graham