-2

I can't quite figure out the code to do this, there are similar posts: Repeating elements in list comprehension

but I want to repeat a value in the list by the value in the list

In [219]:

l = [3,1]

[i for x in range(i) for i in l]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-219-84d6f25dfd96> in <module>()
      1 l = [3,1]
      2 
----> 3 [i for x in range(i) for i in l]

TypeError: 'tuple' object cannot be interpreted as an integer

What I want is a list like so:

[3,3,3,1]

Also can someone explain the error.

Note I am running python 3.3 here

Community
  • 1
  • 1
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • 1
    Note that the first for-loop runs first, so `i` is undefined there. – Ashwini Chaudhary Aug 06 '14 at 09:33
  • 1
    Regarding the error, you must have initialized `i` to a tuple before running the list comprehension, hence you'll get that error in Pytton 3. `range((1, 2)) --> TypeError: 'tuple' object cannot be interpreted as an integer` – Ashwini Chaudhary Aug 06 '14 at 09:36

2 Answers2

3
[x for x in l for _ in range(x)]
# Out[5]: [3, 3, 3, 1]

But I prefer more verbose, yet more straigforward (literal) functions from itertools:

from itertools import chain, repeat
list(chain.from_iterable(repeat(x, x) for x in l))
m.wasowski
  • 6,329
  • 1
  • 23
  • 30
  • I really like your second answer, it's more readable to me, I'm actually using this to reduce the verbosity in an asnwer I posted: http://stackoverflow.com/questions/25152470/computing-spell-lengths-of-data-based-on-equality-in-pandas, for some reason the list comprehension doesn't work for the `spell_len` method in my answer but your itertools one did – EdChum Aug 06 '14 at 09:51
0

Yet another solution.

l = [3,1]

ll = reduce(lambda a, b: a + [b] * b, l, [])

print ll
user189
  • 604
  • 3
  • 11
  • Where does reduce come from? – EdChum Aug 06 '14 at 09:49
  • Please take a look at that https://docs.python.org/2/library/functions.html#reduce – user189 Aug 06 '14 at 09:50
  • Is this missing from python 3? I'm using python 3.3 – EdChum Aug 06 '14 at 09:52
  • @EdChum Apparently, in Python3, you have to import it from functools (and of course use print as a function). – user189 Aug 06 '14 at 09:54
  • 3
    This is very inefficient solution - with every iteration you create `b` new lists, than concatenate them (slow!) to `a` and each other. If you profile it, you find that your solution has around `O(n^2)` complexity... – m.wasowski Aug 06 '14 at 10:27