• Home
  • Split a list into multiple lists based on a specific element – Python

Split a list into multiple lists based on a specific element – Python

To split a list into multiple lists based on a specific element, you can use the following approach:

  1. Create an empty list called result that will store the resulting lists
  2. Iterate over the input list and for each element, check if it is the specific element you want to split on
  3. If it is, append the current sublist to the result list and start a new sublist
  4. If it is not, append the element to the current sublist
  5. When you reach the end of the input list, append the final sublist to the result list

Here is an example of this approach:

def split_on_element(input_list, element):
result = []
current_sublist = []
for elem in input_list:
if elem == element:
result.append(current_sublist)
current_sublist = []
else:
current_sublist.append(elem)
result.append(current_sublist)
return result

input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
split_list = split_on_element(input_list, 5)
print(split_list) # [[1, 2, 3, 4], [6, 7, 8, 9, 10]]

This will split the input list into two sublists, with the first sublist containing the elements before the element 5 and the second sublist containing the elements after 5.