Python : Reverse Order Of List

47,760

Solution 1

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)

Solution 2

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)

Share:
47,760
Muhammed Bhikha
Author by

Muhammed Bhikha

Updated on July 09, 2022

Comments

  • Muhammed Bhikha
    Muhammed Bhikha almost 2 years

    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?