# Python – Step Frequency of elements in List

Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + `defaultdict()`
The combination of above functions can be used to perform this task. In this, we just initialize list with a default value and increment its frequency using a loop.

 `# Python3 code to demonstrate  ` `# Step Frequency of elements in List ` `# using loop + defaultdict() ` `from` `collections ``import` `defaultdict ` ` `  `# Initializing loop  ` `test_list ``=` `[``'gfg'``, ``'is'``, ``'best'``, ``'gfg'``, ``'is'``, ``'life'``] ` ` `  `# printing original list  ` `print``(``"The original list is : "` `+` `str``(test_list)) ` ` `  `# Step Frequency of elements in List ` `# using loop + defaultdict() ` `res_d ``=` `defaultdict(``int``) ` `res ``=` `[] ` `for` `ele ``in` `test_list: ` `    ``res_d[ele] ``+``=` `1` `    ``res.append(res_d[ele]) ` ` `  `# printing result  ` `print` `(``"Step frequency of elements is : "` `+` `str``(res)) `

Output :

```The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life']
Step frequency of elements is : [1, 1, 1, 2, 2, 1]
```

Method #2 : Using `list comprehension + enumerate()`
The combination of above functions can be used to solve this problem. In this we just iterate and store the counter using enumerate().

 `# Python3 code to demonstrate  ` `# Step Frequency of elements in List ` `# using list comprehension + enumerate() ` `from` `collections ``import` `defaultdict ` ` `  `# Initializing loop  ` `test_list ``=` `[``'gfg'``, ``'is'``, ``'best'``, ``'gfg'``, ``'is'``, ``'life'``] ` ` `  `# printing original list  ` `print``(``"The original list is : "` `+` `str``(test_list)) ` ` `  `# Step Frequency of elements in List ` `# using list comprehension + enumerate() ` `res ``=` `[test_list[ : idx ``+` `1``].count(ele) ``for` `(idx, ele) ``in` `enumerate``(test_list)] ` ` `  `# printing result  ` `print` `(``"Step frequency of elements is : "` `+` `str``(res)) `

Output :

```The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life']
Step frequency of elements is : [1, 1, 1, 2, 2, 1]
```

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.