-3

I have a list l = [100, 200, 300, 400, 500]

I want to loop through it using two variables:

   for x, y in ???:
      print x, y

I want to get the result like:

100, 200
200, 300
300, 400
400, 500

I know there are many ways to do it, but I am not sure which one is elegant. Please let me know if you know any elegant way.

stanleyli
  • 1,427
  • 1
  • 11
  • 28
  • Possible duplicate of [What is the most "pythonic" way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – Brendan Abel Aug 02 '16 at 23:14

1 Answers1

3

Elegance is relative. Use zip:

for x, y in zip(l, l[1:]):
    print x, y
donkopotamus
  • 22,114
  • 2
  • 48
  • 60