3

I'm trying to reverse various lists, I feel my code is some what elegant, can any one make it more beautiful ?

board = [1,2,3,5]
board = [config[len(config)-1-i] for i,house in enumerate(config)]
print board

#expected output [5,3,2,1]
David Hancock
  • 1,063
  • 4
  • 16
  • 28

2 Answers2

2

This should do what you want:

In [2]: board[::-1]
Out[2]: [5, 3, 2, 1]

See here : https://docs.python.org/2/library/functions.html#slice

And for a generator, see here : https://docs.python.org/2/library/itertools.html#itertools.islice

jrjc
  • 21,103
  • 9
  • 64
  • 78
1

Use:

In[45]: board = [1,2,3,5]

In[46]: board.reverse()

In[47]: board
Out[47]: [5, 3, 2, 1]
gtlambert
  • 11,711
  • 2
  • 30
  • 48