Search code examples
pythonfor-loopiteratornested-loopsstring-interning

Iterate through three lists multiple times sequentially picking one element from a list in each iteration


I want to iterate through each of the three lists sequentially picking one element from each list in every iteration.

subjects=["Americans","Indians"]
verbs=["plays","watch"]
objects=["Baseball","cricket"]
for i,j,k in zip(subjects,verbs,objects):
    print(i,j,k)

The above code gives the output as follows:

Americans plays Baseball

Indians watch cricket

But the intended output is:

Americans play Baseball.

Americans play Cricket.

Americans watch Baseball.

Americans watch Cricket.

Indians play Baseball.

Indians play Cricket.

Indians watch Baseball.

Indians watch Cricket.

Solution

  • You can iterate as such for the solution:

    subjects=["Americans","Indians"] 
    verbs=["plays","watch"] 
    objects=["Baseball","cricket"]
    
    
    for s in subjects:
        for v in verbs:
            for o in objects:
                print(s,v,o+".")