user880248
user880248

Reputation:

Python turning a list into a list of tuples

What I want to accomplish:

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

What I have thought of so far:

done = []

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

Is there a more Pythonic way of accomplishing this?

Upvotes: 5

Views: 231

Answers (3)

jamylak
jamylak

Reputation: 133514

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')]

Upvotes: 8

Robson França
Robson França

Reputation: 661

Another way to accomplish the same result: list comprehensions

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

Upvotes: 6

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

done = [(el, x) for el in [a, b, c, d]]

Upvotes: 13

Related Questions