Search code examples
pythonlist-comprehension

Generate a list using list comprehension in Python which gives the count of numbers and put the number at the specific index


Suppose I have a list

input = [4, 4, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 2]

This list can contain (repeating) numbers from 0 to n (here n=4). Can I generate a list using list comprehension, where the value at index is equal to the count of that number in list a For e.g., output list in above scenario would be

output = [0, 2, 7, 4, 2]

Explanation

here
output[0] = 0 #since we don't have any 0 in input list
output[1] = 2 #since we have two 1's in input list
output[2] = 7 #since we have seven 2's in input list
output[3] = 4 #since we have four 3's in input list
output[4] = 2 #since we have two 4's in input list

Solution

  • You could use collections.Counter:

    from collections import Counter
    
    inp = [4, 4, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 2]
    
    c = Counter(inp)
    output = [c[k] for k in range(max(c)+1)]
    

    NB. do not use input as a variable name, this is a python builtin

    output:

    [0, 2, 7, 4, 2]