Equivalents of Ruby's "!" methods?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Aug 26 01:47:16 CEST 2008


On Mon, 25 Aug 2008 17:04:07 +0000, Grzegorz Staniak wrote:

> On 25.08.2008, Terry Reedy <tjreedy at udel.edu> wroted:
> 
>> The newish sorted() and reversed() built-ins were meant to complement
>> list.sort and list.reverse, not replace them.
> 
> BTW, is there a reason why sorted() on a list returns a list, while
> reversed() on the same list returns an iterator?

Until the day that somebody discovers how to sort a list without seeing 
all the items first, there's no point in sorted() returning an iterator. 
It has to generate a copy of the entire list to sort it, and so might as 
well just return the list -- there's no advantage to turning it into an 
iterator after you've already built the list.

On the other hand, reversed() can supply it's items lazily. Although it 
does need access to the entire source, it doesn't need to return an 
entire list. It can just return the items one at a time, starting from 
the last one.

That however does mean there's one gotcha: if you mutate a list after 
calling sorted() on it, the result of the sorted() doesn't change. But 
the same doesn't hold for reversed():

>>> L = range(5)
>>> it = reversed(L)  # expecting [4, 3, 2, 1, 0] as an iterator
>>> it.next()
4
>>> L[3] = 'mutate'
>>> it.next()
'mutate'

The solution to that is simple: call list(reversed(L)). Or don't mutate 
the original.



-- 
Steven



More information about the Python-list mailing list