5

In the following example, I have a list containing words. I wanto to split it into multiple sublists. Is there a more efficient approach in Python 3?

elements = ['hello', 'world', '.', 'hello', 'you', '.', 'hello', 'me', '.']

result = []
buffer = []
for element in elements:
    if element is not '.':
        buffer.append(element)
    else:
        result.append(buffer)
        buffer = []

print(result)
# Results into: [['hello', 'world'], ['hello', 'you'], ['hello', 'me']]

Some more test cases:

elements_1 = ['hello', 'world', '.', 'hello', 'you', '.', 'hello', 'me', '.']
elements_2 = ['hello', 'world', '.', 'hello', 'you', '.', 'hello', 'me', '.', '.']
elements_3 = ['hello', 'world', '.', 'hello', 'you', '.', 'hello', 'me', '.', '.', 'hello', 'everybody', '.']

def split_into_sublists(elements):
    result = []
    buffer = []
    for element in elements:
        if element is not '.':
            buffer.append(element)
        else:
            if len(buffer) > 0:
                result.append(buffer)
            buffer = []
    return result

print(split_into_sublists(elements_1)) # [['hello', 'world'], ['hello', 'you'], ['hello', 'me']]
print(split_into_sublists(elements_2)) # [['hello', 'world'], ['hello', 'you'], ['hello', 'me']]
print(split_into_sublists(elements_3)) # [['hello', 'world'], ['hello', 'you'], ['hello', 'me'], ['hello', 'everybody']]
Answered question