How to Use reversed() Function in Python: Syntax and Examples
The
reversed() function in Python returns an iterator that accesses the given sequence in reverse order. You can use it with sequences like lists, strings, or tuples by passing the sequence as an argument to reversed().Syntax
The reversed() function takes one argument, which is a sequence (like a list, string, or tuple), and returns an iterator that yields elements in reverse order.
reversed(sequence): sequence is the input you want to reverse.- The result is an iterator, so you can convert it to a list or loop through it.
python
reversed(sequence)
Example
This example shows how to reverse a list and a string using reversed(). It converts the iterator to a list or string to display the reversed sequence.
python
my_list = [1, 2, 3, 4] reversed_list = list(reversed(my_list)) my_string = "hello" reversed_string = ''.join(reversed(my_string)) print(reversed_list) print(reversed_string)
Output
[4, 3, 2, 1]
olleh
Common Pitfalls
One common mistake is expecting reversed() to return a list directly. It returns an iterator, so you must convert it to a list or another sequence type to see the reversed elements all at once.
Also, reversed() works only on sequences that support indexing and have a known length. It does not work on sets or dictionaries directly.
python
wrong = reversed([1, 2, 3]) print(wrong) # This prints an iterator object, not the reversed list right = list(reversed([1, 2, 3])) print(right) # This prints the reversed list
Output
<list_reverseiterator object at 0x7f...>
[3, 2, 1]
Quick Reference
- Input: Any sequence (list, string, tuple)
- Output: An iterator that yields elements in reverse order
- Convert to list: Use
list(reversed(sequence)) - Convert to string: Use
''.join(reversed(string)) - Not for: Sets, dictionaries (use other methods)
Key Takeaways
Use
reversed() to get an iterator that goes through a sequence backwards.Convert the iterator to a list or string to see all reversed elements at once.
reversed() works only on sequences with indexing and length.It does not work directly on sets or dictionaries.
Remember that
reversed() does not change the original sequence.