firetheRookie firetheRookie - 1 month ago 6
Python Question

Find sum of occurrence of elements in sliced-list mapped to index of element

I have the following list:

my_list=['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']

I want to create a new list which is used to count the sum of all occurrences of a unique value in my_list as my_list is iterated over. The iteration should start with the first item in my_list and go over all items in my_list.

For example, I want a list that looks like this:

[1, 2, 3, 4, 1, 2, 1, 2, 1]


You may use list.count() to find the occurence of word on the sliced list along with list comprehension:

>>> my_list= ['John', 'John', 'John', 'John', 'Joe', 'Joe', 'Kevin', 'Kevin', 'Bryan']
>>> [my_list[:i].count(name) for i, name in enumerate(my_list, 1)]
[1, 2, 3, 4, 1, 2, 1, 2, 1]

Here, my_list[:i].count(name) will give the count of occurrence of name in my_list from 0th to ith index (excluding the value at ith index). To know about enumerate(), refer the document. I am passing start = 1 with enumerate which means value of i will start from 1.

Example related to slicing and count:

>>> my_list[:6]      # Values upto `5`th index
['John', 'John', 'John', 'John', 'Joe', 'Joe']  
>>> my_list[:6].count('John')   # occurence of `John` in the list

Edit: This equivalent conversion of this list comprehension expression to the for loop will be:

my_count = []                #    v  Means index `i` starting from `1`
for i, name in enumerate(my_list, 1):
    word_count = my_list[:i].count(name)

Here my_count will hold the same value which was retuned by the list comprehension.