English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico do Python

Controle de fluxo do Python

Funções do Python

Tipos de Dados do Python

Operações de arquivos do Python

Objetos e classes do Python

Data e hora do Python

Conhecimentos avançados do Python

Manual de referência do Python

Uso e exemplo do reversed() em Python

Python built-in functions

A função reversed() retorna um iterador reverso da sequência fornecida.

A sintaxe da função reversed() é:

reversed(seq)

Parâmetro reversed()

A função reversed() aceita um único parâmetro:

  • seq -Ordem invertida

A sequence is an object that supports the sequence protocol __len__() and __getitem__() methods. For example,tuple,string,list,rangeetc.

We can also use reversed() on any object that implements __reverse__().

reversed() return value

The reversed() function returns an iterator that accesses the given sequence in reverse order.

Example1: Using reversed() in strings, tuples, lists, and ranges

# For string
seq_string = 'Python'
print(list(reversed(seq_string)))
# For tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple)))
# For range
seq_range = range(5, 9)
print(list(reversed(seq_range)))
# For list
seq_list = [1, 2, 4, 3, 5]
print(list(reversed(seq_list)))

Output result

['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]

In our example, we use the list() function to convert the iterator returned by reverse() to a list.

Example2: Custom object reversed()

class Vowels:
    vowels = ['a', 'e', 'i', 'o', 'u']
    def __reversed__(self):
        return reversed(self.vowels)
v = Vowels()
print(list(reversed(v)))

Output result

['u', 'o', 'i', 'e', 'a']

Python built-in functions