Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 733
Stas Avatar asked Oct 10 '10 08:10

Stas


People also ask

What is the difference between list and list comprehension?

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.

What do you mean by Extend () in the list?

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

What are append () and extend () list methods?

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.

What is list comprehension method?

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.


3 Answers

Stacked LCs.

[y for x in a for y in [x[0]] * x[1]]
like image 88
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 19:09

Ignacio Vazquez-Abrams


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']
like image 14
tokland Avatar answered Sep 23 '22 19:09

tokland


>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k in range(n)]
['a', 'a', 'b', 'b', 'c']
like image 6
sdcvvc Avatar answered Sep 24 '22 19:09

sdcvvc