October 2018
Beginner to intermediate
466 pages
12h 2m
English
The reversed() function takes any sequence as input, and returns a copy of that sequence in reverse order. It is normally used in for loops when we want to loop over items from back to front.
Similar to len, reversed calls the __reversed__() function on the class for the parameter. If that method does not exist, reversed builds the reversed sequence itself using calls to __len__ and __getitem__, which are used to define a sequence. We only need to override __reversed__ if we want to somehow customize or optimize the process, as demonstrated in the following code:
normal_list = [1, 2, 3, 4, 5]class CustomSequence: def __len__(self): return 5 def __getitem__(self, index): return f"x{index}"class FunkyBackwards: def __reversed__(self): ...