-1

I have a list of numbers that I want to iterate over in pairs, but without skipping items. For instance:

myList = [1,2,3,4,5]
for one,two in myList:
    print(one,two)

which I want to print,

1,2
2,3
3,4
4,5

I am currently using the list index and am manually getting the additional items, but I want to know if there is a "proper" way to do this.

  • 2
    Funny enough, [this question](https://stackoverflow.com/questions/21752610/iterate-every-2-elements-from-list-at-a-time) is the answer to this one. – DeepSpace May 18 '21 at 22:00

2 Answers2

2

The way that works is usually the proper way...

You could in principle zip the list with a deferred slice of itself:

myList = [1,2,3,4,5]
for one,two in zip(myList, myList[1:]):
    print(one,two, sep=",")

Note that zip ends on the shortest given iterable, so it will finish on the shorter slice; no need to also shorten the full myList parameter.

Joffan
  • 1,485
  • 1
  • 13
  • 18
0

You can zip the list with itself, just offset by 1 item.

myList = [1,2,3,4,5]
for x, y in zip(myList, myList[1:]):
    print(f'{x},{y}')

which prints:

1,2
2,3
3,4
4,5
James
  • 32,991
  • 4
  • 47
  • 70