This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Programming FAQ about "How do I iterate over a sequence in reverse order?" should be more precise about `reversed`
Type: enhancement Stage:
Components: Documentation Versions: Python 3.9, Python 3.8
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: Dominik V., docs@python
Priority: normal Keywords:

Created on 2020-04-20 21:38 by Dominik V., last changed 2022-04-11 14:59 by admin.

Messages (1)
msg366889 - (view) Author: Dominik Vilsmeier (Dominik V.) * Date: 2020-04-20 21:38
https://docs.python.org/3/faq/programming.html#how-do-i-iterate-over-a-sequence-in-reverse-order

It contains the following example:

    for x in reversed(sequence):
        ...  # do something with x ...

With the note:

> This won’t touch your original sequence, but build a new copy with reversed order to iterate over.

The part about "build a new copy" is not correct in a sense that `reversed` just returns an iterator over the original sequence. This has mainly two consequences:

1. It can't be indexed, i.e. `reversed(sequence)[0]` doesn't work.
2. Changing the original sequence after `r = reversed(sequence)` has been constructed, is reflected in `r` when iterating over it.

So the sentence should be changed into something like:

> This creates an iterator object that can be used to iterate over the original sequence in reverse order.

Then for the second example about `sequence[::-1]` it would be good to mention the difference to `reversed`, namely that this version *does* create a copy of the original list (in reverse order). It could also be used as an opportunity to show how to reverse a string, since that is a very popular question on StackOverflow.

Also the various mentions of Python versions 2.3 and 2.4 seem strange since this is documentation about Python 3 and those version are anyway very old. So they should be left out as well.
History
Date User Action Args
2022-04-11 14:59:29adminsetgithub: 84525
2020-04-20 21:38:25Dominik V.create