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...
we can create a list of tuples using list and tuples directly.
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.
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.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Use the builtin function zip()
:
In Python 3:
z = list(zip(x,y))
In Python 2:
z = zip(x,y)
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With