Sorted Returns List and Reversed Returns Iterator

Peter Otten __peter__ at web.de
Fri Aug 22 02:28:41 EDT 2008


++imanshu wrote:

> On Aug 22, 8:40 am, John Machin <sjmac... at lexicon.net> wrote:
>> On Aug 22, 1:35 pm, John Machin <sjmac... at lexicon.net> wrote:
>>
>>
>>
>> > On Aug 22, 12:12 pm, "++imanshu" <himanshu.g... at gmail.com> wrote:
>>
>> > > Hi,
>>
>> > > Is there a reason why two similarly named functions Sorted and
>> > > Reversed return different types of data or is it an accident.
>>
>> > You seem to have an interesting notion of "similarly named".
>> > name0[-2:] == name1[-2:], perhaps? The two functions (eventually, in
>> > the case of "reversed") return data in the order one would expect from
>> > their names.
>>
>> > >>> x = [1, 3, 5, 2, 4, 6]
>> > >>> sorted(x)
>> > [1, 2, 3, 4, 5, 6]
>> > >>> reversed(x)
>>
>> > <listreverseiterator object at 0x00AA5550>
>>
>> > >>> list(reversed(x))
>> > [6, 4, 2, 5, 3, 1]-
>>
>> Sorry; having re-read the message subject:
>>
>> reversed came later; returning an iterator rather than a list provides
>> more flexibility.
>>
>> Cheers,
>> John
> 
> I agree. Iterator is more flexible. Together and both might have
> returned the same types.

It's easy to generate a reversed sequence on the fly but impractical for a
sorted one. Python is taking the pragmatic approach here.

Peter



More information about the Python-list mailing list