Python | List Element Count with Order

Sometimes, while working with lists or numbers we can have a problem in which we need to attach with each element of list, a number, which is the position of that element’s occurrence in that list. This type of problem can come across many domains. Let’s discuss a way in which this problem can be solved.

Method : Using defaultdict() + loop
We can perform this task using defaultdict() and loop by carefully assigning and incrementing order of elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# List Element Count Order
# using defaultdict() + loop
from collections import defaultdict
  
# initialize list 
test_list = [1, 4, 1, 5, 4, 1, 5]
  
# printing original list 
print("The original list : " + str(test_list))
  
# List Element Count Order
# using defaultdict() + loop
temp = defaultdict(int)
res = []
for ele in test_list:
    temp[ele] += 1
    res.append((ele, temp[ele]))
  
# printing result
print("List elements with their order count : " + str(res))

chevron_right


Output :

The original list : [1, 4, 1, 5, 4, 1, 5]
List elements with their order count : [(1, 1), (4, 1), (1, 2), (5, 1), (4, 2), (1, 3), (5, 2)]


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.