Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to get the previous element

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) ...
like image 364
user792036 Avatar asked Aug 22 '12 15:08

user792036


People also ask

How do I extract the last element of a list?

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.

How do I find the previous value of a variable in Python?

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.

Does the index location 1 reverse the list or print the last element?

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.


2 Answers

What about the simple (obvious) solution?

def offset(iterable):
    prev = None
    for elem in iterable:
        yield prev, elem
        prev = elem
like image 76
mgilson Avatar answered Oct 21 '22 17:10

mgilson


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)
like image 44
sloth Avatar answered Oct 21 '22 15:10

sloth