Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over all pairs of consecutive items in a list [duplicate]

Given a list

l = [1, 7, 3, 5] 

I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5), i.e.

for i in xrange(len(l) - 1):     x = l[i]     y = l[i + 1]     # do something 

I would like to do this in a more compact way, like

for x, y in someiterator(l): ... 

Is there a way to do do this using builtin Python iterators? I'm sure the itertools module should have a solution, but I just can't figure it out.

like image 399
flonk Avatar asked Jan 23 '14 08:01

flonk


People also ask

How do you print consecutive items in a list Python?

To iterate over all pairs of consecutive items in a list with Python, we can use zip with a for loop. We call zip with l and a list with l starting with the 2nd element. Then we loop through the list of tuples returned by zip and print the first and second item in each tuple.

Can you loop through two lists at once Python?

Use the izip() Function to Iterate Over Two Lists in Python It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.


2 Answers

Just use zip

>>> l = [1, 7, 3, 5] >>> for first, second in zip(l, l[1:]): ...     print first, second ... 1 7 7 3 3 5 

If you use Python 2 (not suggested) you might consider using the izip function in itertools for very long lists where you don't want to create a new list.

import itertools  for first, second in itertools.izip(l, l[1:]):     ... 
like image 102
sberry Avatar answered Sep 17 '22 18:09

sberry


Look at pairwise at itertools recipes: http://docs.python.org/2/library/itertools.html#recipes

Quoting from there:

def pairwise(iterable):     "s -> (s0,s1), (s1,s2), (s2, s3), ..."     a, b = tee(iterable)     next(b, None)     return izip(a, b) 

A General Version

A general version, that yields tuples of any given positive natural size, may look like that:

def nwise(iterable, n=2):                                                           iters = tee(iterable, n)                                                          for i, it in enumerate(iters):                                                        next(islice(it, i, i), None)                                                    return izip(*iters)    
like image 32
Bach Avatar answered Sep 18 '22 18:09

Bach