Python | Group strings at particular element in list

Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let’s discuss certain way in which this problem can be performed.

Method : Using groupby() + list comprehension + lambda
This task can be performed using combination of above functions. In this, we group the elements using groupby() and decision of grouping element logic is done in form of lambda function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Group strings at particular element in list
# using groupby() + list comprehension + lambda
from itertools import groupby
  
# initialize lists
test_list = ['gfg', 'is', 'best', 'and', 'is', 'popular']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initialize partition element
ele = 'is'
  
# Group strings at particular element in list
# using groupby() + list comprehension + lambda
res = [list(j) for i, j in groupby(test_list, lambda x:x == ele) if not i]
  
# printing result
print("Resultant list after grouping : " + str(res))

chevron_right


Output :

The original list is : ['gfg', 'is', 'best', 'and', 'is', 'popular']
Resultant list after grouping : [['gfg'], ['best', 'and'], ['popular']]


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.