5

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?

3 Answers 3

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

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')]
5
  • 1
    Interesting approach. I thought of using zip() with [x]*len([a, b, c, d]), but I didn't know about itertools.
    – user880248
    Apr 1, 2012 at 6:22
  • >>> x = 'apple' >>> y = [a,b,c,d] >>> zip(y,[x]*len(y)) That also works, i was thinking of quick ways of doing it using the array directly without saving it to a varible.
    – jamylak
    Apr 1, 2012 at 6:27
  • 1
    I just read this blog post about repeat, it's very fast. I would guess one or both of these is faster than the other methods. The second one is very clever.
    – agf
    Apr 1, 2012 at 7:00
  • Maybe they are faster in other situations but I don't think these are any faster in this case. Not much can be done to speed up this process since it is so simple the list comprehension does the bare minimum i believe.
    – jamylak
    Apr 1, 2012 at 7:26
  • stackoverflow.com/a/101310/880248 This trick is relevant to not saving the values directly by instead saving a generator.
    – user880248
    Apr 2, 2012 at 6:45
6

Another way to accomplish the same result: list comprehensions

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.