Using reversed() to change the order
There are times when we need a sequence reversed. Python offers us two approaches to this: the reversed()
function and slices with reversed indices.
For an example, consider performing a base conversion to hexadecimal or binary. The following is a simple conversion function:
def digits(x, b): if x == 0: return yield x % b for d in to_base(x//b, b): yield d
This function uses a recursion to yield the digits from the least significant to the most significant. The value of x%b
will be the least significant digits of x
in the base b
.
We can formalize it as following:
In many cases, we'd prefer the digits to be yielded in the reverse order. We can wrap this function with the reversed()
function to swap the order of the digits:
def to_base(x, b): return reversed(tuple(digits(x, b)))
Note
The reversed()
function produces an iterable, but the argument value must be a sequence object. The function then yields the items from that object...