In this short tutorial we will learn how to divide a Python list objects to multiple sublists.
Example list object
All examples in this tutorial will be based on the following programming languages list :
Divide a list based with delimiter
In this simple case, the after being split, the elements will be written to a string delimited by commas followed by a space:
', '.join (all_lang_lst)
The output will be:
Split a list by condition
We might want to split a list into multiple sub lists based on a simple condition.
Here’s the output:
Note: as shown above we can use the join() function to convert any list to a string.
Split Python lists by substring
In a similar fashion we can divide the list based on whether its element contains a specific sub string. We’ll start by defining a function:
def splt_by_substrng (my_lst, my_str): subs_lst =  subs_lst_other = for e in my_lst: if my_str in e: subs_lst.append(e) else: subs_lst_other.append(e) return subs_lst, subs_lst_other
We’ll now call the function that we have just defined. In our case we would like to split programming languages containing the substring ‘ja’ into a separated list. The function will return two lists.
print("Here are the split lists: " + str(splt_by_substrng(all_lang_lst , "Ja")))
The result will be:
Find the difference between two lists
Another way to split lists is simply by subtracting. We can convert our lists to Python sets and simply subtract them:
other_lst= set(all_lang_lst)- set(data_lang)