reversed Iterates Backwards Without Copying

reversed hands back a one-shot reverse iterator instead of copying, leaving the sequence untouched, while slicing [::-1] allocates a re-usable list.

PythonData Integrity

Code

pythonsnippet
16 lines
digits = [1, 2, 3, 4]

# reversed returns a reverse iterator: it copies nothing and never mutates the original list
print("reversed:", list(reversed(digits)))
print("original:", digits)

# the [::-1] slice is equivalent but builds a new list
print("slice copy:", digits[::-1])

# the same works on strings
print("text:", "".join(reversed("deploy")))

# reversed is an iterator: it can be consumed only once
it = reversed(digits)
print("first pass:", list(it))
print("second pass:", list(it))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

reversed: [4, 3, 2, 1]
original: [1, 2, 3, 4]
slice copy: [4, 3, 2, 1]
text: yolped
first pass: [4, 3, 2, 1]
second pass: []

How it works

Top-level bindings digits, it hold the demo state — nothing sits inside a function scope.

Points of care

  • Only built-in APIs, which leaves no supply chain to vet.

Using it

The demo output is labeled (reversed:, original:, slice copy:), so every line of output can be traced to the operation that made it.

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `digits`, `it`.