Search code examples
pythontupleszip

Get a tuple from lists with zip() in Python


I'm stuck in this code, I have to get a tuple from three lists by using the zip function and a for loop (no index or enumerate (mandatory)). I need to get this:

answer = (
    ("John", "London", "Cloudy"),
    ("Bruno", "San Paulo", "Sunny"),
    ("Mike", "Sevilla", "Windy"),
)

And I tried this (inside a function):

answer = []
for item in zip([name], [place], [weather]):
    answer.append(item)
    answer = tuple(answer)
    return answer

The thing is, I'm getting this output:

((["John", "Bruno", "Mike"], ["London", "San Paulo", "Sevilla"], ["Cloudy", "Sunny", "Windy"]),)

So, not only the brackets inside are a problem but also the order. Can someone give a hint? Thank you.


Solution

  • Don't put [] around the variables. Now you're zipping those lists, not the contents of the variables.

    Just use:

    answer = tuple(zip(name, place, weather))