Well, you can use the itertools module to group elements according to whether they are spaces or not.
For example, you can use the str.ispace function as a predicate to group elements:
list1 = ["I", "am", "happy", " ", "and", "fine", " ", "and", "good"] for key, group in itertools.groupby(list1, key=str.isspace): print(key, list(group))
You are getting:
False ['I', 'am', 'happy'] True [' '] False ['and', 'fine'] True [' '] False ['and', 'good']
Based on this, you can create a list by excluding groups whose key is True ( isspace returned True ):
result = [list(group) for key, group in itertools.groupby(list1, key=str.isspace) if not key] print(result)
You get a list of lists:
[['I', 'am', 'happy'], ['and', 'fine'], ['and', 'good']]
If you are not familiar with understanding lists, you can use a loop:
result = [] for key, group in itertools.groupby(list1, key=str.isspace): if not key: result.append(list(group))
You can unpack this result into 3 variables:
sublist1, sublist2, sublist3 = result