12

Possible Duplicate:
How can I reverse a list in python?

How do I reverse the order of a list: eg. I have lines.sort(key = itemgetter(2))

that is a sorted list. What if I wanted that list exactly as it is ordered, but in reverse order?

Community
  • 1
  • 1
Muhammed Bhikha
  • 4,881
  • 9
  • 36
  • 47
  • When marking something as a duplicate, it's useful to give a link to what it's a duplicate of. Here's a link for this case: http://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python – Linguist May 08 '15 at 15:34

2 Answers2

26
lines.sort(key=itemgetter(2), reverse=True)

or if you just want to reverse the list

lines.reverse()

or if you want to copy the list into a new, reversed list

reversed(lines)
Katriel
  • 120,462
  • 19
  • 136
  • 170
  • 11
    The last example returns an iterable, not a list. You'd have to use `list(reversed(lines))` for that to become a list again. It's easier to use a negative stride slice instead: `lines[::-1]`. – Martijn Pieters Nov 23 '12 at 14:16
  • 1
    And the nice thing about negative strides is that it works for other types as well: `tuple`, `str` ... – mgilson Nov 23 '12 at 14:18
22

Do you want sort the list (in place) such that the greatest elements are first and the smallest elements are last (greatest and "smallest" determined by your key or cmp function)? If so, use the other answers. (If you want to sort out of place, use sorted instead).

A simple way to reverse the order (out of place) of any list is via slicing:

reverse_lst = lst[::-1]

Note that this works with other sequence objects as well (tuple and str come to mind immediately)

mgilson
  • 300,191
  • 65
  • 633
  • 696