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.
# 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)) |
The original list is : ['gfg', 'is', 'best', 'and', 'is', 'popular'] Resultant list after grouping : [['gfg'], ['best', 'and'], ['popular']]
Recommended Posts:
- Python | Group tuples in list with same first value
- Python | Group Anagrams from given list
- Python | Group elements on break positions in list
- Python | Group list elements based on frequency
- Python | Group consecutive list elements with tolerance
- Python | Group elements at same indices in a multi-list
- Python | Group by matching second tuple value in list of tuples
- Python | Remove empty strings from list of strings
- Python | Tokenizing strings in list of strings
- Python | Merge list of tuple into list by joining the strings
- Python | Filter list of strings based on the substring list
- Python | Convert list of strings to list of tuples
- Python | Filter a list based on the given list of strings
- Python | Convert list of tuples to list of strings
- Python | Replace elements in second list with index of same element in first list
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.



