Python turns a list into a list of tuples

What I want to do:

[a, b, c, d] -> [ (a, x), (b, x), (c, x), (d, x) ]

What I was thinking so far:

done = []

for i in [a, b, c, d]:
   done.append((i, x))

Is there a more pythonic way to accomplish this?

+5
source share
3 answers
done = [(el, x) for el in [a, b, c, d]]
+13
source

Using itertools.repeat

>>> x = 'apple'
>>> a,b,c,d = 'a','b','c','d'
>>> from itertools import repeat    
>>> zip([a,b,c,d],repeat(x))
[('a', 'apple'), ('b', 'apple'), ('c', 'apple'), ('d', 'apple')]

Using itertools.product

>>> from itertools import product
>>> list(product([a,b,c,d],[x]))
[('a', 'apple'), ('b', 'apple'), ('c', 'apple'), ('d', 'apple')]
+8
source

Another way to accomplish the same result: a list of concepts

done = [(i,x) for i in [a,b,c,d]]
+6
source

All Articles