Skip to content Skip to sidebar Skip to footer

List.extend And List Comprehension

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 w

Solution 1:

Stacked LCs.

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

Solution 2:

An itertools approach:

import itertools

def flatten(it):
    return itertools.chain.from_iterable(it)

pairs = [['a',2], ['b',2], ['c',1]]
flatten(itertools.repeat(item, times) for (item, times) inpairs)
# ['a', 'a', 'b', 'b', 'c']

Solution 3:

>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k inrange(n)]
['a', 'a', 'b', 'b', 'c']

Solution 4:

If you prefer extend over list comprehensions:

a = []
for x, y in l:
    a.extend([x]*y)

Solution 5:

import operator
a = [['a',2], ['b',2], ['c',1]]
nums = [[x[0]]*x[1] for x in a]
nums = reduce(operator.add, nums)

Post a Comment for "List.extend And List Comprehension"