[New-bugs-announce] [issue40345] Programming FAQ about "How do I iterate over a sequence in reverse order?" should be more precise about `reversed`

Dominik V. report at bugs.python.org
Mon Apr 20 17:38:25 EDT 2020


New submission from Dominik V. <dominik.vilsmeier1123 at gmail.com>:

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.

----------
assignee: docs at python
components: Documentation
messages: 366889
nosy: Dominik V., docs at python
priority: normal
severity: normal
status: open
title: Programming FAQ about "How do I iterate over a sequence in reverse order?" should be more precise about `reversed`
type: enhancement
versions: Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40345>
_______________________________________


More information about the New-bugs-announce mailing list