zer0uno
zer0uno

Reputation: 8030

Comparison between sorted()/reversed()

I have some questions about the ideas that brought to make some choices in the creation of Python.

First of all the 2 builtin methods sorted() and reversed(), why does the former return a list instead the latter returns a iterator? Why making this difference?

Upvotes: 2

Views: 91

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74685

In order to sort a list, we need to get all of the elements and put them in the right order. So whatever kind of iterable is passed to sorted will be converted into a list. Once the list is already created, there's no advantage to returning an iterator.

reversed is different; if you pass it a list, there's no need for it to create a new list that's back to front, it is more efficient to return a generator that will access elements from the original list on demand.

Note that reversed doesn't do any sorting on the values in a sequence, it reverses the order in which the elements appear.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124060

sorted() and reversed() do entirely different things.

reversed() can give you the reverse of a sequence very efficiently. Types like list, str and range implement a __reversed__ method that is used to give access to the same sequence in reverse (simply translating indices to count from the end instead of the start); if not implemented the __getitem__ and __len__ methods are used and reversed() does the transformation itself.

Important here is that the relative order of the elements doesn't change, only the direction in which you iterate over it is different. In that respect reversed() is the inverse of iter(), but only for types that have a fixed length.

Sorting on the other hand always has to build a new list as the relative order of the elements has to be altered. You are no longer just getting elements one by one without having to know what other elements are in the sequence.

Upvotes: 4

Related Questions