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?
Difference between list comprehension and for loop. The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code.
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
Python append() method adds an element to a list, and the extend() method concatenates the first list with another list (or another iterable). When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one.
List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
Stacked LCs.
[y for x in a for y in [x[0]] * x[1]]
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) in pairs)
# ['a', 'a', 'b', 'b', 'c']
>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k in range(n)]
['a', 'a', 'b', 'b', 'c']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With