list.extend and list comprehension

Stas picture Stas · Oct 10, 2010 · Viewed 21.9k times · Source

When I need to add several identical items to the list I use list.extend:

a = ['a', 'b', 'c']
a.extend(['d']*3)

Result

['a', 'b', 'c', 'd', 'd', 'd']

But, how to do the similar with list comprehension?

a = [['a',2], ['b',2], ['c',1]]
[[x[0]]*x[1] for x in a]

Result

[['a', 'a'], ['b', 'b'], ['c']]

But I need this one

['a', 'a', 'b', 'b', 'c']

Any ideas?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 10, 2010

Stacked LCs.

[y for x in a for y in [x[0]] * x[1]]