How to use Reversed Function in PythonPython Basics


The reversed() function returns an iterator object of the given sequence in the reverse order.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# string
seq = 'ABCDEF'
print(seq)
print(list(reversed(seq)))

# tuple
seqTuple = ('M', 'I', 'T')
print(seqTuple)
print(list(reversed(seqTuple)))

Output:

ABCDEF
['F', 'E', 'D', 'C', 'B', 'A']
('M', 'I', 'T')
['T', 'I', 'M']

Syntax

reversed(sequence)

Parameters

Name Description
sequence Any iterable object

Return Value

It returns a reversed iterator object.


In this example we will show how to use reversed() function in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# String parameter
seqString = 'Basketball'
for i in reversed(seqString):
    print(i,end=' ')
print()


# Tuple parameter
seqTuple = ('R', 'k', 'n', 's', 'o', 'b')
for i in reversed(seqTuple):
    print(i,end=' ')
print()

# Range function parameter
seqRange = range(5, 9)
for i in reversed(seqRange):
    print(i,end=' ')
print()


# List parameter
seqList = [1, 2, 4, 3, 5]
for i in reversed(seqList):
    print(i,end=' ')

Output:

l l a b t e k s a B 
b o s n k R 
8 7 6 5 
5 3 4 2 1 

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us