Python - For loops with multiple indices

50 Views Asked by At

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!

2

There are 2 best solutions below

0
C.Nivs On

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
0
Frank Yellin On

itertools.pairwise was designed just for this

from itertools import pairwise

for a, b in pairwise(mylist):
    print(a, b)