Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Reverse Order Of List [duplicate]

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?

like image 657
Muhammed Bhikha Avatar asked Nov 23 '12 14:11

Muhammed Bhikha


People also ask

How do I reverse a list order in Python?

Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.

How do I reverse the order of a list in Python 3?

Use reversed() and slicing to create reversed copies of your lists. Use iteration, comprehensions, and recursion to create reversed lists. Iterate through your lists in reverse order.

How do you mirror a list in Python?

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.

How do you reverse the order of a list in Python for loop?

3) Using for loop Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.


2 Answers

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)
like image 168
Katriel Avatar answered Oct 13 '22 02:10

Katriel


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)

like image 43
mgilson Avatar answered Oct 13 '22 00:10

mgilson