Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python have `reversed`?

Why does Python have the built-in function reversed?

Why not just use x[::-1] instead of reversed(x)?


Edit: @TanveerAlam pointed out that reversed is not actually a function, but rather a class, despite being listed on the page Built-in Functions.

like image 622
Garrett Avatar asked Sep 13 '25 21:09

Garrett


2 Answers

>>> a= [1,2,3,4,5,6,7,8,9,10]
>>> a[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> reversed(a)
<listreverseiterator object at 0x10dbf5390>

The first notation is generating the reverse eagerly; the second is giving you a reverse iterator, which is possibly cheaper to acquire, as it has potential to only generate elements as needed

like image 62
Enrico Granata Avatar answered Sep 16 '25 10:09

Enrico Granata


reversed returns a reverse iterator.

[::-1] asks the object for a slice

Python objects try to return what you probably expect

>>> [1, 2, 3][::-1]
[3, 2, 1]
>>> "123"[::-1]
'321'

This is convenient - particularly for strings and tuples.

But remember the majority of code doesn't need to reverse strings.

The most important role of reversed() is making code easier to read and understand.

The fact that it returns an iterator without creating a new sequence is of secondary importance

From the docs

PEP 322: Reverse Iteration A new built-in function, reversed(seq)(), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.

>>>
>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1

Compared to extended slicing, such as range(1,4)[::-1], reversed() is easier to read, runs faster, and uses substantially less memory.

Note that reversed() only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with list().

>>>
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
like image 33
John La Rooy Avatar answered Sep 16 '25 11:09

John La Rooy