You can use a list comprehension like you attempted to, you just need a slight modification to account for different spots in the list:
b = [[a[i-1], a[i]] for i in range(1, len(a))]
Output:
[['foo', 'bar'], ['bar', 'cat'], ['cat', 'dog']]
Since you want to pair "touching" items the a[i-1]
and a[i]
accomplish this. Then just loop through each i
in len(a)
. We use range(1,len(a))
instead of range(len(a))
, however, because we don't want to pair the first value of a
with something before it because it is the first value.
An arguably cleaner solution would be to use zip
, but it depends on preference:
b = [list(i) for i in zip(a, a[1:])]
In this case we use a[1:]
in order to offset that list so that the pairs are correct.