Reverse a list, string, tuple in Python (reverse, reversed)
In Python, you can reverse the items of lists (
list) with using
reversed(), and slicing. If you want to reverse strings (
str) and tuples (
reversed() or slice.
Here, the following contents will be described.
- List type method
reverse()reverses the original list
- Built-in function
reversed()returns a reverse iterator
- Reverse with slicing
- Reverse strings and tuples
If you want to sort in ascending or descending order instead of in reverse order, see the following article.
List type method
reverse() reverses the original list
reverse() is a list type method.
reverse() is a destructive process that reverse the original list in place.
org_list = [1, 2, 3, 4, 5] org_list.reverse() print(org_list) # [5, 4, 3, 2, 1]
print(org_list.reverse()) # None
reversed() returns a reverse iterator
reversed() is a built-in function.
reversed() generates an iterator that retrieves elements in reverse order
reversed () returns an iterator that retrieves the items in reverse order. The original list remains unchanged.
org_list = [1, 2, 3, 4, 5] reverse_iterator = reversed(org_list) print(org_list) # [1, 2, 3, 4, 5] print(type(reverse_iterator)) # <class 'list_reverseiterator'>
reversed() returns an iterator, not a list.
You can just use it in a
for i in reversed(org_list): print(i) # 5 # 4 # 3 # 2 # 1
If you want to get a list in reverse order, use
list() to convert the iterator to a list.
new_list = list(reversed(org_list)) print(org_list) print(new_list) # [1, 2, 3, 4, 5] # [5, 4, 3, 2, 1]
Reverse with slicing
You can also use a slicing to reverse lists.
In slicing, specify a range or increment in the form
stop are omitted, the whole list is selected, and by setting
-1, items can be obtained one by one from the back.
You can get the reverse list by
org_list = [1, 2, 3, 4, 5] new_list = org_list[::-1] print(org_list) print(new_list) # [1, 2, 3, 4, 5] # [5, 4, 3, 2, 1]
See the following post for details of slicing.
Reverse strings and tuples
Since strings and tuples are immutable, there is no
reverse() method that update the original object.
If you want to reverse strings or tuples, use
reversed() or slices.
Since iterators cannot be converted directly to strings, when using
reversed(), convert the iterator to a list containing one character and then join them with
org_str = 'abcde' new_str_list = list(reversed(org_str)) print(new_str_list) # ['e', 'd', 'c', 'b', 'a'] new_str = ''.join(list(reversed(org_str))) print(new_str) # edcba
The method using slicing is the same as for lists. This is easier than using
new_str = org_str[::-1] print(new_str) # edcba
tuple () to convert an iterator to a tuple.
org_tuple = (1, 2, 3, 4, 5) new_tuple = tuple(reversed(org_tuple)) print(new_tuple) # (5, 4, 3, 2, 1)
The method using slicing is the same as for lists.
new_tuple = org_tuple[::-1] print(new_tuple) # (5, 4, 3, 2, 1)