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?
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.
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.
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With