'How to get forwaard moving combination of a list in python?

I have a following list lst = [100,200,300,400]

I need the following output [(100, 200), (200, 300), (300, 400)]

I did some research and used itertools.combinations library for that

[c for c in itertools.combinations(lst, 2)]

if I use the above code I get the following output which produces all combinations. [(100, 200), (100, 300), (100, 400), (200, 300), (200, 400), (300, 400)]

I don't want all the combinations, I only want forward moving combinations how can I get the desired output?



Solution 1:[1]

If you're on Python 3.10, you can use itertools.pairwise(). Otherwise, you can use zip():

lst = [100,200,300,400]
list(zip(lst, lst[1:]))

This outputs:

[(100, 200), (200, 300), (300, 400)]

Solution 2:[2]

YOu could achieve this using pure python code.

lst = [100,200,300,400]

new_lst = [(lst[a],lst[a+1]) for a in range(len(lst)) if a<len(lst)-1]
print(new_lst)

OUTPUT

[(100, 200), (200, 300), (300, 400)]

AS @hilberts_drinking_problem comment you can use itertools.pairwise also.

from itertools import pairwise
lst = [100,200,300,400]

new_list = list(pairwise(lst))
print(new_list)

OUTPUT:


[(100, 200), (200, 300), (300, 400)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sharim Iqbal