Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous in yield operations - python

Recently i have been using the 'yield' in python. And I find generator functions very useful. My query is that, is there something which could decrement the imaginative cursor in the generator object. Just how next(genfun) moves and outputs +i'th item in the container, i would like to know if there exists any function that may call upon something like previous(genfun) and moves to -1th item in the conatiner.

Actual Working

def wordbyword():
  words = ["a","b","c","d","e"]
  for word in words:
    yield word

getword = wordbyword()

next(getword)
next(getword)

Output's

a
b

What I would like to see and achieve is

def wordbyword():
  words = ["a","b","c","d","e"]
  for word in words:
    yield word

getword = wordbyword()

next(getword)
next(getword)
previous(getword)

Expected Output

a
b
a

This may sound silly, but is there someway there is this previous in generator, if not why is it so?. Why not we could decrement the iterator, or am I ignorant of an existing method, pls shower some light. What can be the closest way to implement what I have here in hand.

like image 863
PIngu Avatar asked Dec 22 '22 15:12

PIngu


1 Answers

No there is no such function to sort of go back in a generator function. The reason is that Python does not store up the previous value in a generator function natively, and as it does not store it, it also cannot perform a recalculation.

For example, if your generator is a time-sensitive function, such as

def time_sensitive_generator():
    yield datetime.now()

You will have no way to recalculate the previous value in this generator function.

Of course, this is only one of the many possible cases that a previous value cannot be calculated, but that is the idea.

If you do not store the value yourself, it will be lost forever.

like image 168
burningalc Avatar answered Dec 28 '22 11:12

burningalc