Out-of-place rearrangement

Sometimes an in situ sort or reversal is not what is required. For example, it may cause a function argument to be modified, giving the function confusing side effects. For out-of-place equivalents of the reverse() and sort() list methods you can use the reversed() and sorted() build-in functions which return a reverse iterator and a new sorted list respectively. For example:

>>> x = [4, 9, 2, 1]
>>> y = sorted(x)
>>> y
[1, 2, 4, 9]
>>> x
[4, 9, 2, 1]

We can also use the reversed() function:

>>> p = [9, 3, 1, 0]
>>> q = reversed(p)
>>> q
<list_reverseiterator object at 0x1007bf290>
>>> list(q)
[0, 1, 3, 9]

Notice how we used a list constructor to evaluate the result of reversed(). This is because reversed() returns an iterator, a topic which we'll cover in much more detail later.

These functions have the advantage that they'll work on any finite iterable source object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset