'Python Counter to list of elements

Now to flatten Counter element i'm using the code

import operator
from collections import Counter
from functools import reduce

p = Counter({'a': 2, 'p': 1})
n_p = [[e] * p[e] for e in p]
f_p = reduce(operator.add, n_p)

# result: ['a', 'a', 'p']

So i'm wonder, if it could be done more directly.



Solution 1:[1]

This is Counter.elements

p = Counter({'a': 2, 'p': 1})
p.elements()  # iter(['a', 'a', 'p'])
list(p.elements())  # ['a', 'a', 'p']
''.join(p.elements())  # 'aap'

Note that (per the docs)

Elements are returned in arbitrary order

So you may want to sort the result to get a stable order.

Solution 2:[2]

You can use a nested list comprehension:

[i for a, b in p.items() for i in [a]*b]

Output:

['a', 'a', 'p']

Solution 3:[3]

With just for loop:

from collections import Counter

p = Counter({'a': 2, 'p': 1})
plist = []
for tup in p.items():
    for n in range(tup[1]):         
        plist.append(tup[0])
print(plist)

output:

['a', 'a', 'p']
>>> 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 PythonProgrammi