user1936752
user1936752

Reputation: 858

Split a list into two lists upon seeing a specific element

Suppose I have a list in Python. Whenever I encounter 'a' in the list, I should break the list into two lists and put the 'a' either at the end of the first list or the start of the second. How do I keep doing this until I have several lists, each with at most one occurrence of 'a'?

Here is my attempt. It works but is pretty ugly.

input_list = [0, 1, 'a', 'b', 'c', 2]
partitioned_list = []
temp_list =[]
for item in input_list:
     temp_list.append(item)
     if item == 'a':
         partitioned_list.append(temp_list)
         temp_list = []
partitioned_list.append(temp_list)

I get as output [[0, 1, 'a'],['b', 'c', 2]] for the input_list given above.

Upvotes: 0

Views: 105

Answers (1)

Cezar Todirisca
Cezar Todirisca

Reputation: 190

I hope that I understood what you wanted:

input_list = [0, 1, 'a', 'b', 'c', 2, 'a', 21, 'c', 'a', 'a','b','a']
partitioned_lists = []
start = 0
for index, item in enumerate(input_list):
    if item == 'a':
        partitioned_lists.append(input_list[start:index+1])
        start = index + 1
    
if start != len(input_list):
    partitioned_lists.append(input_list[start:])
print(partitioned_lists)

Upvotes: 1

Related Questions