Python | Consecutive remaining elements in list

Sometimes, while working with Python list, we can have a problem in which we need to get the consecutive elements count remaining( including current ), to make certain decisions beforehand. This can be a potential subproblem of many competitive programming competitions. Let’s discuss a shorthand which can be applied to solve this problem.

Method : Using range() + from_iterable() + groupby() + list comprehension
This task can be performed and solved using combination of above functions. In this, we first use groupby function to form groups and convert them into reverse ranges using range(). This all is converted to generator to avoid creation of nested list and then final list is obtained using from_iterable().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Consecutive remaining elements in list
# using range() + from_iterable() + groupby() + list comprehension
from itertools import chain, groupby
  
# initialize list
test_list = [4, 4, 5, 5, 5, 1, 1, 2, 4]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Consecutive remaining elements in list
# using range() + from_iterable() + groupby() + list comprehension
temp = (range(len(list(j)), 0, -1) for i, j in groupby(test_list))
res = list(chain.from_iterable(temp))
  
# printing result
print("Consecutive remaining elements list : " + str(res))

chevron_right


Output :

The original list is : [4, 4, 5, 5, 5, 1, 1, 2, 4]
Consecutive remaining elements list : [2, 1, 3, 2, 1, 2, 1, 1, 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.