Python reversed() method returns an iterator that accesses the given sequence in the reverse order.
Example:
Python
# creating a list
cars = ["nano", "swift", "bolero", "BMW"]
# reversing the list
reversed_cars = list(reversed(cars))
#printing the list
print(reversed_cars)
Output['BMW', 'bolero', 'swift', 'nano']
Python reversed() Method Syntax
reversed(sequence)
Parameter :
- sequence : Sequence to be reversed.
Return : Returns an iterator that accesses the given sequence in the reverse order.
How to use reversed function in Python?
reversed() method is very easy to use and it returns an iterator that accesses the list in reverse order. Let’s understand it better with an example.
Example:
In the given example, we are reversing elements of the list with reversed() function in Python.
Python
my_list = ["apple", "banana", "cherry", "date"]
reversed_list = list(reversed(my_list))
print(reversed_list)
Output['date', 'cherry', 'banana', 'apple']
More Python reversed() Method Examples
Let’s see some of the other common scenarios for reversed() method.
1. Python reversed() with Built-In Sequence Objects
In the given example we have used reversed() with tuple and range. When using reversed with these objects we need to use the list() method to convert the output from reversed() to list.
Python
# For tuple
seqTuple = ('g', 'e', 'e', 'k', 's')
print(list(reversed(seqTuple)))
# For range
seqRange = range(1, 5)
print(list(reversed(seqRange)))
Output['s', 'k', 'e', 'e', 'g']
[4, 3, 2, 1]
2. Python reversed() with for loop in Python
In this example, we are using reversed() function to show it’s working with Python loops.
Python
# Create a string
str = "Reversed in Python"
# Reverse the string and print its characters in reverse order
for char in reversed(str):
print(char, end="")
Output
nohtyP ni desreveR
3. Python reversed() in Python with custom objects
In this example, we are creating a class gfg which includes a list of vowels we are using the reversed function to reverse the vowels.
Python
class gfg:
vowels = ['a', 'e', 'i', 'o', 'u']
# Function to reverse the list
def __reversed__(self):
return reversed(self.vowels)
# Main Function
if __name__ == '__main__':
obj = gfg()
print(list(reversed(obj)))
Output['u', 'o', 'i', 'e', 'a']
4. Python reversed() method with List
In this example, we are reversing a list of vowels with the reversed function in Python.
Python
vowels = ['a', 'e', 'i', 'o', 'u']
print(list(reversed(vowels)))
Output['u', 'o', 'i', 'e', 'a']
5. Python reversed() method with string
In this example, we are reversing a string with the reversed function in Python.
Python
str = "Geeksforgeeks"
print(list(reversed(str)))
Output['s', 'k', 'e', 'e', 'g', 'r', 'o', 'f', 's', 'k', 'e', 'e', 'G']
Exception in reversed() function
In this example, we are showing the exception in reversed() function.
Python
# Create a list
lst = [1, 2, 3]
# Reverse the list using the `reversed` function
reversed_lst = reversed(lst)
# Print the reversed elements one by one using the `next` function
print(next(reversed_lst))
print(next(reversed_lst))
print(next(reversed_lst))
# Attempting to print the next element will raise a StopIteration exception
print(next(reversed_lst)) # Exception
Output
3
2
1
StopIteration
print(next(my_list_rev)) # Exception
Line 13 in <module> (Solution.py)
We have covered the definition, syntax and different uses of reversed() method in Python. Python reversed() function is very important function to access sequence from the end.
reversed() method can be used to reverse a set, list,tuple, etc in Python.
Python reversed() Method – FAQs
Can you provide Example of Using reversed()
with a List?
You can use the reversed()
function to reverse the elements of a list. Here’s an example:
original_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(original_list))
print(reversed_list) # Output: [5, 4, 3, 2, 1]
How Does reversed()
Differ from the reverse()
Method?
reversed()
:- Returns an iterator that accesses the given sequence in reverse order.
- Does not modify the original sequence.
original_list = [1, 2, 3, 4, 5]
reversed_iterator = reversed(original_list)
reversed_list = list(reversed_iterator)
print(original_list) # Output: [1, 2, 3, 4, 5]
print(reversed_list) # Output: [5, 4, 3, 2, 1]
reverse()
:- Modifies the original list to reverse its elements.
original_list = [1, 2, 3, 4, 5]
original_list.reverse()
print(original_list) # Output: [5, 4, 3, 2, 1]
What Data Types Can We Apply the reversed()
Method To?
The reversed()
function can be applied to:
- Lists
- Tuples
- Strings
- Range objects
It returns an iterator that accesses the sequence in reverse order.
How to Reverse a String Using reversed()
You can reverse a string by using reversed()
and then joining the characters back together:
original_string = "Hello, world!"
reversed_string = ''.join(reversed(original_string))
print(reversed_string) # Output: "!dlrow ,olleH"
Can We Use reversed()
with Tuples and Sets?
original_tuple = (1, 2, 3, 4, 5)
reversed_tuple = tuple(reversed(original_tuple))
print(reversed_tuple) # Output: (5, 4, 3, 2, 1)
- Tuples: Yes, you can use
reversed()
with tuples, and it will return an iterator. - Sets: No, you cannot use
reversed()
with sets because sets are unordered collections and do not maintain any specific order.
Similar Reads
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read
Python int() Function
Python int() function returns an integer from a given object or converts a number in a given base to a decimal. Example: In this example, we passed a string as an argument to the int() function and printed it. C/C++ Code age = "21" print("age =", int(age)) Output: age = 21Python
4 min read
Python len() Function
len() function returns number of items in an object that can be characters, words, or elements in a sequence. Let’s start with a simple example to understand the len() functions with strings: [GFGTABS] Python s = "GeeksforGeeks" # Use len() to find the length of the string length = len(s)
2 min read
Python map() function
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
4 min read
Python - max() function
Python max() function returns the largest item in an iterable or the largest of two or more arguments. It has two forms. max() function with objectsmax() function with iterablePython max() function With ObjectsUnlike the max() function of C/C++, the max() function in Python can take any type of obje
4 min read
memoryview() in Python
Python memoryview() function returns the memory views objects. Before learning more about memoryview() function let's see why do we use this function. Why do we use memoryview() function? As Memory view is a safe way to expose the buffer protocol in Python and a memoryview behaves just like bytes in
4 min read
Python min() Function
Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter. Example: Find Python min integer from the list [GFGTABS] Python numbers = [23,25,65,21,98] print(min(numbers)) [/GFGTABS]Output 21Python min() Function Syntaxmin(a, b, c, ..., key=fu
4 min read
Python next() method
Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. C/C++ Code l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2. It has been replaced
4 min read
Python oct() Function
Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode c
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modu
2 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python range() function
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. [GFGTABS] Python for i in range(5): print(i, end="
7 min read
Python reversed() Method
Python reversed() method returns an iterator that accesses the given sequence in the reverse order. Example: [GFGTABS] Python # creating a list cars = ["nano", "swift", "bolero", "BMW"] # reversing the list reversed_cars = list(reversed(cars)) #printing the li
4 min read
round() function in Python
Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this
6 min read
Python slice() function
In this article, we will learn about the Python slice() function with the help of multiple examples. Example C/C++ Code String = 'Hello World' slice_obj = slice(5,11) print(String[slice_obj]) Output: World A sequence of objects of any type (string, bytes, tuple, list, or range) or the object which i
5 min read
Python sorted() Function
sorted() function returns a new sorted list from the elements of any iterable like (e.g., list, tuples, strings ). It creates and returns a new sorted list and leaves the original iterable unchanged. Let's start with a basic example of sorting a list of numbers using the sorted() function. [GFGTABS]
3 min read
Python str() function
The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Let’s take a simple example to converting an Intege
4 min read
sum() function in Python
The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. [GFGTABS] Python arr = [1, 5, 2] print(sum(arr)) [/GFGTABS]Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything
3 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
zip() in Python
The zip() function in Python combines multiple iterables such as lists, tuples, strings, dict etc, into a single iterator of tuples. Each tuple contains elements from the input iterables that are at the same position. Let’s consider an example where we need to pair student names with their test scor
3 min read