How to create a zip of zip of a list in python. I need it for a double for loop

I have the following lists:

mylist1 = ["peru", "germany", "japan"]
mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]]
mylist3=[[1,2],[3,4],[5]]

and I want to print

peru
lima
1
cusco
2

germany
berlin
3
munich
4

japan
tokyo
5

One zip command looks like:

list=list(zip(mylist1,mylist2,mylist3))

for country,cities,nums in list:
    print(country)
    for city in cities:
         print(city)
    for num in nums:
         print(num)

But as you can guess, it won’t output what I want. So I thought of a double zip like
list = list(zip(mylist1,zip(mylist2,mylist3))), and then

for country,info in list:
    print(country)
    for city,num in info:
         print(city)
         print(num)

But it doesn’t work. I do need 2 for loops. One for the country and a second one to handle the other info.

>Solution :

You can do it like this using three zips in total, although you can do it in a simpler way if you use indices with enumerate (assuming the lists have the same length):

mylist1 = ["peru", "germany", "japan"]
mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]]
mylist3 = [[1,2], [3,4], [5]]

for country, (cities, numbers) in zip(mylist1, zip(mylist2, mylist3)):
    print(country)
    for city, number in zip(cities, numbers):
        print(city)
        print(number)

Leave a Reply