I would like an enumerate
-like functional on iterators which yields the pair (previous_element, current_element)
. That is, given that iter
is
i0, i1, i1, ...
I would like offset(iter)
to yield
(None, i0), (i0, i1), (i1, i2) ...
To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.
There is no way to know the previous value of a variable without assigning to the object another variable. Only the presence of references keeps an object alive in memory. The garbage collector disposes of the object, when the reference count of the object reaches zero.
If you do my_list[-1] this returns the last element of the list. Negative sequence indexes represent positions from the end of the array. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
What about the simple (obvious) solution?
def offset(iterable):
prev = None
for elem in iterable:
yield prev, elem
prev = elem
To put more itertools on the table:
from itertools import tee, izip, chain
def tee_zip(iterable):
a, b = tee(iterable)
return izip(chain([None], a), b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With