python: create list of tuples from lists

Question:

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…

Asked By: amyassin

||

Answers:

Use the builtin function zip():

In Python 3:

z = list(zip(x,y))

In Python 2:

z = zip(x,y)
Answered By: Udi

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)]
Answered By: mjhm

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)]
Answered By: mal-wan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.