-1

I'm trying to access multiple items in a list as they relate to one another. I would like to access list item 0 and 1, item 1 & 2. I'm familiar with for loops, but only accessing

list = [A, B, C, D, E, F] etc.
for i in list:
     print(i)
     print (i+1)

Result:

AB BC CD DE EF

I would also prefer to not get F'null' or "FA" as a tail.

Any advice? Thanks!

Jared
  • 1

2 Answers2

3

itertools.pairwise was designed just for this

from itertools import pairwise

for a, b in pairwise(mylist):
    print(a, b)
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
2

You could just zip the collection with itself offset by 1:

mylist = list('ABCDEF')

for a, b in zip(mylist, mylist[1:]):
    print(a, b)

A B
B C
C D
D E
E F
C.Nivs
  • 12,353
  • 2
  • 19
  • 44