pythonloopsfor-loopcounteralternate

How to have double counter variable in Python loop?


x=[1,2,3,4,5]
y=[6,7,8,9,10]
for a,b in x,y:
    print(a,b)

expected output:

1,6
2,7
3,8
4,9
5,10

But I know two count variables are not possible. Help me by giving better alternative code to achieve the same.


Solution

  • You can use zip here.

    for a,b in zip(x,y):
        print(a,b,sep=', ')
    

    Using range

    for i in range(len(x)):
        print(x[i],y[i],sep=', ')
    

    If you have unequal length list use itertools.zip_longest.

    for i,j in itertools.zip_longest(x,y,fillvalues=' '):
        print(i,j,sep=', ')