combinations: A better way to iterate through a pair of values in a Python list. If you want to iterate through a pair of values in a list and the order does not matter ( (a,b) is the same as (b, a) ), use itertools. combinations instead of two for loops.
Care has to be taken while pairing the last element with the first one to form a cyclic pair. zip function can be used to extract pairs over the list and slicing can be used to successively pair the current element with the next one for the efficient pairing.
Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line.
You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).
From the itertools
recipes:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for v, w in pairwise(a):
...
To do that you should do:
a = [5, 7, 11, 4, 5]
for i in range(len(a)-1):
print [a[i], a[i+1]]
Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
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