Skip to content
Advertisement

How do I iterate over two lists?

I have troubles in using for loops in Python. I wrote this code:

x=5
people=['Mary','Joe']
genders=['she','he']

for person in people:
    print(person)
    for gender in genders:
        if x > 0:
            print("{} is happy".format(gender)) 

and the output is:

Mary
she is happy
he is happy
Joe
she is happy
he is happy

But I would like the output to be:

Mary
she is happy
Joe
he is happy

Is there a way to make the for loop iterate over first “Mary” and “she” and then “Joe” and “he” ?

I thank you in advance.

Advertisement

Answer

Why, you can go with zip(). Here is a cleaner solution.

people=['Mary','Joe']
genders=['she','he']
for person,gender in zip(people,genders):
    print(person)
    print("{} is happy".format(gender)) 

Output:

Mary
she is happy
Joe
he is happy
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement