Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
And it should produce
[5, 7]
[7, 11]
[11, 4]
[4, 5]
Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
And it should produce
[5, 7]
[7, 11]
[11, 4]
[4, 5]
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
>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
... print a[n],a[n+1]
...
5 7
7 11
11 4
4 5
An alternative way is itertools.pairwise
(Python 3.10 or later):
from itertools import pairwise
temp = [-39.5, -27.5, -15.5, -3.5, 8.5, 20.5, 32.5, 44.5, 56.5, 68.5, 80.5, 92.5,104.5]
res = list(pairwise(temp))
[(-39.5, -27.5), (-27.5, -15.5), (-15.5, -3.5), (-3.5, 8.5), (8.5, 20.5), (20.5, 32.5), (32.5, 44.5), (44.5, 56.5), (56.5, 68.5), (68.5, 80.5), (80.5, 92.5), (92.5, 104.5)]