[python] python: create list of tuples from lists

I have two lists:

x = ['1', '2', '3']
y = ['a', 'b', 'c']

and I need to create a list of tuples from these lists, as follows:

z = [('1','a'), ('2','b'), ('3','c')]

I tried doing it like this:

z = [ (a,b) for a in x for b in y ]

but resulted in:

[('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]

i.e. a list of tuples of every element in x with every element in y... what is the right approach to do what I wanted to do? thank you...

EDIT: The other two duplicates mentioned before the edit is my fault, indented it in another for-loop by mistake...

This question is related to python list tuples

The answer is


You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to tuples

Append a tuple to a list - what's the difference between two ways? How can I access each element of a pair in a pair list? pop/remove items out of a python tuple Python convert tuple to string django: TypeError: 'tuple' object is not callable Why is there no tuple comprehension in Python? Python add item to the tuple Converting string to tuple without splitting characters Convert tuple to list and back How to form tuple column from two columns in Pandas