How to iterate over all pairs of consecutive items in a list with Python?

Sometimes, we want to iterate over all pairs of consecutive items in a list with Python.

In this article, we’ll look at how to iterate over all pairs of consecutive items in a list with Python.

How to iterate over all pairs of consecutive items in a list with Python?

To iterate over all pairs of consecutive items in a list with Python, we can use zip with a for loop.

For instance, we write:

l = [1, 7, 3, 5]
for first, second in zip(l, l[1:]):
    print(first, second)

We call zip with l and a list with l starting with the 2nd element.

Then we loop through the list of tuples returned by zip and print the first and second item in each tuple.

Therefore, we get:

1 7
7 3
3 5

Conclusion

To iterate over all pairs of consecutive items in a list with Python, we can use zip with a for loop.