Python | Ways to Spilt 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
# Python code to split the list # by some value into two lists. # List initialisation list = ['Geeks', 'forgeeks', 'is a', 'portal', 'for Geeks'] # Spliting list into first half first_list = list[:list.index('forgeeks')] # Spliting list into second half second_list = list[list.index('forgeeks')+1:] # Printing first list print(first_list) # Printing second list print(second_list) |
['Geeks'] ['is a', 'portal', 'for Geeks']
Method #2: Using dropwhile and set
# Python code to split the list # by some value into two lists. # Importing from itertools import dropwhile # List initialisation lst = ['Geeks', 'forgeeks', 'is a', 'portal', 'for Geeks'] # Using dropwhile to split into second list second_list = list(dropwhile(lambda x: x != 'forgeeks', lst))[1:] # Using set to get difference between two lists first_list = set(lst)-set(second_list) # removing 'split' string first_list.remove('forgeeks') # converting to list first_list = list(first_list) # Printing first list print(first_list) # Printing second list print(second_list) |
['Geeks'] ['is a', 'portal', 'for Geeks']
Recommended Posts:
- Python | Spilt a sentence into list of words
- Python | Ways to sum list of lists and return sum list
- Python | Ways to Convert a 3D list into a 2D list
- Extending a list in Python (5 different ways)
- Python | Ways to rotate a list
- Python | Ways to flatten a 2D list
- Python | Ways to shuffle a list
- Different ways to clear a list in Python
- Python | Multiply all numbers in the list (3 different ways)
- Python | Ways to merge strings into list
- Python | Ways to remove duplicates from list
- Python | Ways to print list without quotes
- Python | Ways to format elements of given list
- Python | Ways to find indices of value in list
- Python | Ways to initialize list with alphabets
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



