Iterate over all pairs of consecutive items in a list

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 make it more compact, for example

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

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

+57
python iterator list
Jan 23 '14 at 8:42
source share
5 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 

As suggested, you can use the izip function in itertools for very long lists where you do not want to create a new list.

 import itertools for first, second in itertools.izip(l, l[1:]): ... 
+76
Jan 23 '14 at 8:45
source share

Take a pairwise look at itertools recipes: http://docs.python.org/2/library/itertools.html#recipes

Quote from there:

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



General version

The general version, which gives tuples of any given positive natural size, may look like this:

 def nwise(iterable, n=2): iters = tee(iterable, n) for i, it in enumerate(iters): next(islice(it, i, i), None) return izip(*iters) 
+28
Jan 23 '14 at 8:46
source share

I would create a grouper generator like this

 def grouper(input_list, n = 2): for i in xrange(len(input_list) - (n - 1)): yield input_list[i:i+n] 

Run Example 1

 for first, second in grouper([1, 7, 3, 5, 6, 8], 2): print first, second 

Exit

 1 7 7 3 3 5 5 6 6 8 

Run Example 1

 for first, second, third in grouper([1, 7, 3, 5, 6, 8], 3): print first, second, third 

Exit

 1 7 3 7 3 5 3 5 6 5 6 8 
+7
Jan 23 '14 at 8:51
source share

You can use zip .

 >>> list(zip(range(5), range(2, 6))) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] 

Like lightning, it creates pairs. So, to mix your two lists, you get:

 >>> l = [1,7,3,5] >>> list(zip(l[:-1], l[1:])) [(1, 7), (7, 3), (3, 5)] 

Then the repetition is performed as

 for x, y in zip(l[:-1], l[1:]): pass 
0
Jan 23 '14 at 8:48
source share

What is below is very simple / readable and does the job, which is also probably the most efficient.

Convert the list to a generator (or better start with an iterator to play with it):

 gen = (x for x in l) 

Convert it to pairs:

 [(x, gen.next()) for x in gen] 

That is all you need.

Of course, better make it a generator and read it as you need:

 ( (x, gen.next()) for x in gen) 
-one
May 21 '16 at 17:06
source share



All Articles