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.
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
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
...