Suppose I have a list l
in python defined as:
l = [x1, x2, x3,...,xn-1, xn],
is there an easy way to create a list l1
:
l1 = [(x1, x2), (x2, x3),...,(xn-1, xn)]?
Suppose I have a list l
in python defined as:
l = [x1, x2, x3,...,xn-1, xn],
is there an easy way to create a list l1
:
l1 = [(x1, x2), (x2, x3),...,(xn-1, xn)]?
You can use a list comprehension and zip
two slices of the list together, which are offset by 1 index
>>> l = list(range(10))
>>> [(a,b) for a,b in zip(l[:-1], l[1:])]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]