Python | Split Sublist Strings
Yet another variation of splitting strings is splitting the strings that are an element of the sublist. This is quite peculiar problem, but one can get the data in this format and knowledge of splitting it anyways quite useful. Let’s discuss certain ways in which this particular task can be performed.
Method #1 : Using list comprehension + split()
This method is the shorthand version of the longer loop version that one could choose to solve this particular problem. We just split the strings fetching the sublist using the loop in list comprehension using split function.
# Python3 code to demonstrate# Split Sublist Strings# using split() + list comprehension # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint("The original list : " + str(test_list)) # using split() + list comprehension# Split Sublist Stringsres = [sub.split() for subl in test_list for sub in subl] # print resultprint("The list after splitting strings : " + str(res)) |
The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]
The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]
Method #2 : Using map() + lambda + split()
This task can also be performed using the combination of above 3 functions. The map function binds the splitting logic to each element which is written using the lambda function that uses split function to perform the split.
# Python3 code to demonstrate# Split Sublist Strings# using map() + lambda + split() # initializing listtest_list = [['GfG is best'], ['All love Gfg'], ['Including me']] # printing original listprint("The original list : " + str(test_list)) # using map() + lambda + split()# Split Sublist Stringsres = list(map(lambda sub: sub[0].split(' '), test_list)) # print resultprint("The list after splitting strings : " + str(res)) |
The original list : [[‘GfG is best’], [‘All love Gfg’], [‘Including me’]]
The list after splitting strings : [[‘GfG’, ‘is’, ‘best’], [‘All’, ‘love’, ‘Gfg’], [‘Including’, ‘me’]]





Please Login to comment...