👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
Given a list
l = [1, 7, 3, 5]
I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5)
, i.e.
for i in xrange(len(l) - 1):
x = l[i]
y = l[i + 1]
# do something
I would like to do this in a more compact way, like
for x, y in someiterator(l): ...
Is there a way to do do this using builtin Python iterators? I"m sure the itertools
module should have a solution, but I just can"t figure it out.
👻 Read also: what is the best laptop for engineering students?
We hope this article has helped you to resolve the problem. Apart from Iterate over all pairs of consecutive items in a list, check other code Python module-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano Iterate over all pairs of consecutive items in a list
- Deutsch Iterate over all pairs of consecutive items in a list
- Français Iterate over all pairs of consecutive items in a list
- Español Iterate over all pairs of consecutive items in a list
- Türk Iterate over all pairs of consecutive items in a list
- Русский Iterate over all pairs of consecutive items in a list
- Português Iterate over all pairs of consecutive items in a list
- Polski Iterate over all pairs of consecutive items in a list
- Nederlandse Iterate over all pairs of consecutive items in a list
- 中文 Iterate over all pairs of consecutive items in a list
- 한국어 Iterate over all pairs of consecutive items in a list
- 日本語 Iterate over all pairs of consecutive items in a list
- हिन्दी Iterate over all pairs of consecutive items in a list
Warsaw | 2023-02-07
Simply put and clear. Thank you for sharing. Iterate over all pairs of consecutive items in a list and other issues with Python functions was always my weak point 😁. Will use it in my bachelor thesis
Berlin | 2023-02-07
Simply put and clear. Thank you for sharing. Iterate over all pairs of consecutive items in a list and other issues with COM PHP module was always my weak point 😁. Will get back tomorrow with feedback
Warsaw | 2023-02-07
COM PHP module is always a bit confusing 😭 Iterate over all pairs of consecutive items in a list is not the only problem I encountered. I just hope that will not emerge anymore