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 Answers3

13
done = [(el, x) for el in [a, b, c, d]]
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
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')]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    Interesting approach. I thought of using zip() with [x]*len([a, b, c, d]), but I didn't know about itertools. –  Apr 01 '12 at 06: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 01 '12 at 06:27
  • 1
    I just read [this blog post about `repeat`](http://rhodesmill.org/brandon/2012/counting-without-counting/), 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 01 '12 at 07: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 01 '12 at 07:26
  • http://stackoverflow.com/a/101310/880248 This trick is relevant to not saving the values directly by instead saving a generator. –  Apr 02 '12 at 06:45
6

Another way to accomplish the same result: list comprehensions

done = [(i,x) for i in [a,b,c,d]]
Robson França
  • 661
  • 8
  • 15