
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Group contiguous strings in List
When it is required to group the contiguous elements of a string that are present in a list, a method is defined that uses ‘groupby’, and ‘yield’.
Example
Below is a demonstration of the same
from itertools import groupby def string_check(elem): return isinstance(elem, str) def group_string(my_list): for key, grp in groupby(my_list, key=string_check): if key: yield list(grp) else: yield from grp my_list = [52, 11, 'py', 'th', 'on', 11, 52, 'i', 's', 18, 'f', 'un', 99] print("The list is :") print(my_list) my_result = [*group_string(my_list)] print("The result is:") print(my_result)
Output
The list is : [52, 11, 'py', 'th', 'on', 11, 52, 'i', 's', 18, 'f', 'un', 99] The result is: [52, 11, ['py', 'th', 'on'], 11, 52, ['i', 's'], 18, ['f', 'un'], 99]
Explanation
A method named ‘string_check’ is defined that takes a list as parameter and checks to see if it belongs to a certain instance type.
Another method named ‘group_string’ is defined that takes a list as parameter and uses yield to return the output using ‘groupby’ method.
Outside the method, a list is defined and is displayed on the console.
The ‘group_string’ is called and the result is assigned to a variable.
This is displayed as output on the console.
- Related Articles
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Python - Contiguous Boolean Range
- Group Shifted Strings in C++
- Python Group Anagrams from given list
- How to remove empty strings from a list of strings in Python?
- Extract numbers from list of strings in Python
- Python – Sort by Rear Character in Strings List
- Python - Custom space size padding in Strings List
- Converting all strings in list to integers in Python
- Python - Ways to merge strings into list
- Python – Strings with all given List characters
- Convert list of strings and characters to list of characters in Python
- Python Program to Group Strings by K length Using Suffix
- How to sort a list of strings in Python?

Advertisements