Categories
Python Answers

How to iterate a list as pair (current, next) in Python?

Spread the love

Sometimes, we want to iterate a list as pair (current, next) in Python.

In this article, we’ll look at how to iterate a list as pair (current, next) in Python.

How to iterate a list as pair (current, next) in Python?

To iterate a list as pair (current, next) in Python, we can use the itertools.tee method.

For instance, we write

import itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)   

to call itertools.tee with the iterable object to return an iterator with the tuples that has the current and next item values each in their own lists.

Then we call next to get the values.

And then we call zip with a and b to combine them into a list with tuples containing the current and next item values and return it.

Conclusion

To iterate a list as pair (current, next) in Python, we can use the itertools.tee method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *