iterations destroy reversed() results
Pierre Fortin
pf at pfortin.com
Fri Sep 1 12:15:45 EDT 2023
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...
Script to illustrate the issue:
/tmp/rev:
orig = [ 'x', 'a', 'y', 'b', 'z', 'c' ]
co = sum( 1 for _ in orig )
print( 'orig', orig, co )
# reversing
rev = reversed(orig)
print( 'before iteration:', [ x for x in rev ] )
# list comprehension was an iteration over 'rev'
print( 'after iteration:', [ x for x in rev ] )
# how this was discovered...
orig = [ 'x', 'a', 'y', 'b', 'z', 'c' ]
rev = reversed(orig)
cr = sum( 1 for _ in rev )
print( 'after sum():', [ x for x in rev ] )
which produces:
$ python /tmp/rev
orig ['x', 'a', 'y', 'b', 'z', 'c'] 6
before iteration: ['c', 'z', 'b', 'y', 'a', 'x']
after iteration: []
after sum(): []
Regards,
Pierre
More information about the Python-list
mailing list