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,023
  • 3
  • 14
  • 26

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
  • 19,301
  • 8
  • 61
  • 75
1

Use:

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

In[46]: board.reverse()

In[47]: board
Out[47]: [5, 3, 2, 1]
gtlambert
  • 11,253
  • 2
  • 28
  • 47