Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: create list of tuples from lists [duplicate]

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...

like image 765
amyassin Avatar asked Sep 05 '11 22:09

amyassin


People also ask

Can I create list of tuples Python?

we can create a list of tuples using list and tuples directly.

Can Python tuples have duplicates?

31.2 Python Collection TypesTuples allow duplicate members and are indexed. Lists Lists hold a collection of objects that are ordered and mutable (changeable), they are indexed and allow duplicate members.

How do I make a list of tuples in a list?

If you're in a hurry, here's the short answer:Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

Can list and tuple have duplicate values?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.


2 Answers

Use the builtin function zip():

In Python 3:

z = list(zip(x,y)) 

In Python 2:

z = zip(x,y) 
like image 173
Udi Avatar answered Sep 29 '22 03:09

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)] 
like image 40
mjhm Avatar answered Sep 29 '22 03:09

mjhm