Skip to content Skip to sidebar Skip to footer

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

Solution 1:

What about the simple (obvious) solution?

defoffset(iterable):
    prev = Nonefor elem in iterable:
        yield prev, elem
        prev = elem

Solution 2:

To put more itertools on the table:

from itertools import tee, izip, chain

deftee_zip(iterable):
   a, b = tee(iterable)
   return izip(chain([None], a), b)

Solution 3:

defpairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...
    see http://docs.python.org/library/itertools.html
    """
    a, b = itertools.tee(iterable)
    b.next()
    return itertools.izip(a, b)

EDIT moved doc string into the function

Solution 4:

defoffset(iter, n=1, pad=None):
    i1, i2 = itertools.tee(iter)
    i1_padded = itertools.chain(itertools.repeat(pad, n), i1)
    return itertools.izip(i1_padded, i2)

@bpgergo + @user792036 = this. Best of two worlds :).

Solution 5:

The best answer I have (and this requires itertools) is

defoffset(iter, n=1):
    # returns tuples (None, iter0), (iter0, iter1), (iter1, iter2) ...
    previous = chain([None] * n, iter)
    return izip(previous, iter)

but I would be interested in seeing if someone has a one-liner (or a better name than offset for this function)!

Post a Comment for "Most Pythonic Way To Get The Previous Element"