iterations destroy reversed() results
Chris Angelico
rosuav at gmail.com
Sun Sep 3 18:42:41 EDT 2023
On Mon, 4 Sept 2023 at 07:44, Pierre Fortin via Python-list
<python-list at python.org> wrote:
>
> Hi,
>
> reversed() results are fine until iterated over, after which the
> results are no longer available. This was discovered after using
> something like this:
>
> rev = reversed( sorted( list ) )
> sr = sum( 1 for _ in rev )
> # rev is now destroyed
>
> So reversed() results can only be iterated once unlike sorted(), etc...
reversed() is like iter(), and should be used the same way:
for item in reversed(list):
If you want to eagerly construct a full reversed list, instead slice the list:
list[::-1]
ChrisA
More information about the Python-list
mailing list