# [Python-Dev] FW: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew24.tex, 1.5, 1.6

Raymond Hettinger python at rcn.com
Sat Nov 8 12:34:05 EST 2003

> ! A new built-in function, \function{reversed(seq)}, takes a sequence
> ! and returns an iterator that returns the elements of the sequence
> ! in reverse order.
> !
> ! \begin{verbatim}
> ! >>> for i in reversed([1,2,3]):
> ! ...    print i
> ! ...
> ! 3
> ! 2
> ! 1
> ! \end{verbatim}
> !
> ! Note that \function{reversed()} only accepts sequences, not
arbitrary
> ! iterators.  If you want to reverse an iterator, convert it to
> ! a list or tuple with \function{list()} or \function{tuple()}.
> !
> ! \begin{verbatim}
> ! >>> input = open('/etc/passwd', 'r')
> ! >>> for line in reversed(list(input)):
> ! ...   print line
> ! ...
> !   ...
> ! \end{verbatim}

It would be nice to present the new features in light of what makes them
desirable.  "for elem in reversed(mylist)"  wins in readability, speed,
and memory performance over "mylist.reverse(); for elem in mylist" or
"for elem in mylist[::-1]".

The readability win is predicated on the notion that half-open intervals
are easier to understand in the forwards direction.  'xrange(n//2, 0,
-1)' is not as instantly understandable as reversed(xrange(1, n//2)).
Using the newer form, anyone can quickly identify the first element,
last element, and number of steps.

> + \item The list type gained a \method{sorted(iterable)} method that
> + returns the elements of the iterable as a sorted list.  It also
accepts
> + the \var{cmp}, \var{key}, and \var{reverse} keyword arguments, same
as
> + the \method{sort()} method.  An  example usage:
> +
> + \begin{verbatim}
> + >>> L = [9,7,8,3,2,4,1,6,5]
> + >>> list.sorted(L)
> + [1, 2, 3, 4, 5, 6, 7, 8, 9]
> + >>> L
> + [9, 7, 8, 3, 2, 4, 1, 6, 5]
> + >>>
> + \end{verbatim}
> +
> + Note that the original list is unchanged; the list returned by
> + \method{sorted()} is a newly-created one.

The keys points here are that 1) any iterable may be used as an input
and 2) list.sorted() is an in-line expression which allows it to be used
in  function arguments, lambda expressions, list comprehensions, and
for-loop specifications:

getlargest = lambda x: list.sorted(x)[-1]
x = [myfunc(v) for v in list.sorted(mydict.itervalues())]
for key in list.sorted(mydict): . . .

> + \item The \module{heapq} module is no longer implemented in Python,
> +       having been converted into C.

And it now runs about 10 times faster which makes it viable for
industrial strength applications.

>   \item The \module{random} module has a new method called
> \method{getrandbits(N)}

Formerly, there was no O(n) method for generating large random numbers.
The new method supports random.randrange() that arbitrarily large
numbers can be generated (important for public key cryptography and
prime number generation).