0

I want to get the elements from a generator in inverse order like it is possible from a list.

Does an approach like [::-1] exist to achieve that? Something like:

for x in map(int,['1','2','3'])[::-1]:
    print(x)

The expected is result is:

3,2,1
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Todd
  • 55
  • 1
  • 5

1 Answers1

1

Just convert it back to a list first. You can't go the other direction with a generator:

for x in list(map(int,['1','2','3']))[::-1]:
    print(x)
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
  • 1
    +1, although its probably worth noting this defeats the lazy eval of generators and there is some danger with infinite generators (as well as slice notation does not work on generators(so his idea wont work ...) ... itertools.islice sort of ... but not for reverse... but there maybe an itertools thing that also reverses :/ – Joran Beasley Aug 09 '19 at 02:35
  • If ['1','2','3'] take a lot of memory, it can not be converted to list before hand – Todd Aug 09 '19 at 02:35
  • 1
    i think you cannot do this without the whole sequence in memory at some point ... (see also: https://stackoverflow.com/questions/5008921/how-do-i-reverse-an-itertools-chain-object) – Joran Beasley Aug 09 '19 at 02:38
  • 1
    @JoranBeasley What would it mean to traverse an infinite generator in reverse? – Barmar Aug 09 '19 at 02:39
  • 1
    it would basically be `while 1: pass;` – Joran Beasley Aug 09 '19 at 02:58