all Python 3Loopsconstruct
for ... in reversed()
for loop
reversed() returns an iterator that walks a sequence backwards. It works with lists, tuples, strings, ranges and any object with __reversed__.
Syntax
for item in reversed(sequence): ...
Unlike the slice sequence[::-1], reversed() copies nothing and returns a lazy iterator, saving memory on long sequences. That is also why it needs a real sequence (with a length and indexing, or __reversed__): you cannot pass a plain generator or a file object to reversed().
Examples
for x in reversed([1,2,3]): print(x, end=" ") # → 3 2 1
print(list(reversed(range(5)))) # → [4, 3, 2, 1, 0]
for ch in reversed("abc"): print(ch, end="") # → cba
t = (10, 20, 30)
for v in reversed(t): print(v, end=" ") # → 30 20 10
print(list(reversed(["a","b","c"]))) # → ['c', 'b', 'a']
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy