Reputation: 127
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.
Upvotes: 1
Views: 251
Reputation: 9
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')
Upvotes: 1
Reputation: 53
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])
Upvotes: 2
Reputation: 6642
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"), ...]
Upvotes: 4