Python | Ways to Split the list by some value
Given a list (may contain either strings or numbers), the task is to split the list by some value into two lists.
The approach is very simple. Split the first half of list by given value, and second half from the same value. There are multiple variations possible from this operation based on the requirement, like dropping the first/some element(s) in second half after the split value etc. Let’s see the different ways we can do this task.
Method #1: Using list index
Python3
# Python code to split the list# by some value into two lists.# List initialisationlist = ['Geeks', 'forgeeks', 'is a', 'portal', 'for Geeks']# Splitting list into first halffirst_list = list[:list.index('forgeeks')]# Splitting list into second halfsecond_list = list[list.index('forgeeks')+1:]# Printing first listprint(first_list)# Printing second listprint(second_list) |
['Geeks'] ['is a', 'portal', 'for Geeks']
Method #2: Using dropwhile and set
Python3
# Python code to split the list# by some value into two lists.# Importingfrom itertools import dropwhile# List initialisationlst = ['Geeks', 'forgeeks', 'is a', 'portal', 'for Geeks']# Using dropwhile to split into second listsecond_list = list(dropwhile(lambda x: x != 'forgeeks', lst))[1:]# Using set to get difference between two listsfirst_list = set(lst)-set(second_list)# removing 'split' stringfirst_list.remove('forgeeks')# converting to listfirst_list = list(first_list)# Printing first listprint(first_list)# Printing second listprint(second_list) |
['Geeks'] ['is a', 'portal', 'for Geeks']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


