1

Hope someone can help me out here. I am using a for loop inside a for loop in Python. That is a nested-for-loop and I want to map the results together once. At the moment the results are displayed correctly once and then incorrectly repeated. This is my code snippet.

for country in ["USA", "Nigeria", "Germany", "India", "Britain"]:
    for code in ["+1", "+234", "+49", "+91", "+44"]:
        print(country, code)
        
print("Done")

The result I am trying to achieve is this one.

USA +1
Nigeria +234
Germany +49
India +91
Britain +44
Done!

But what I am getting at the moment is this one.

USA +1
USA +234
USA +49
USA +91
USA +44
Nigeria +1
Nigeria +234
Nigeria +49
Nigeria +91
Nigeria +44
Germany +1
Germany +234
Germany +49
Germany +91
Germany +44
India +1
India +234
India +49
India +91
India +44
Britain +1
Britain +234
Britain +49
Britain +91
Britain +44
Done

Is there a way I can improve it and get the desired result? I will appreciate your help.

2

3 Answers 3

4

You could zip the countries and codes to match the corresponding elements:

countries = ["USA", "Nigeria", "Germany", "India", "Britain"]
codes = ["+1", "+234", "+49", "+91", "+44"]

for country, code in zip(countries, codes):
    print(country, code)

(or for nicer formatting: print(f"{country} {code}")).

When do loop inside the loop you print each code for each country, which is what you see in your current output.

Zip does exactly what it sounds like, i.e. it acts as a zipper:

list(zip(countries, codes))

gives

[("USA", "+1"), ("Nigeria", "+234"), ...]
Sign up to request clarification or add additional context in comments.

Comments

2

This will work:

countries = ["USA", "Nigeria", "Germany", "India", "Britain"];
codes = ["+1", "+234", "+49", "+91", "+44"];

for i in range(len(countries)):
    print(countries[i], codes[i])

Comments

1

I'm not sure it's what you're waiting for but here is a code that send the result you're waiting for :

country = ["USA", "Nigeria", "Germany", "India", "Britain"]
code = ["+1", "+234", "+49", "+91", "+44"]
for i in range(4):
    print(country[i], code[i])
print('done')

2 Comments

Note that range(4) is [0, 1, 2, 3], i.e. one short
Very much appreciated. It helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.