June 2017
Beginner
352 pages
8h 39m
English
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, ...
Read now
Unlock full access