Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split() + extend()
The combination of above functions can be used to perform this task. In this, we perform the task of split, using split() and add split elements in list using extend().
Python3
# Python3 code to demonstrate working of# Split flatten String List# Using list comprehension + split() + extend() # initializing listtest_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']# printing original listprint("The original list is : " + str(test_list))# Split flatten String List# Using list comprehension + split() + extend()res = [][res.extend(idx.split("-")) for idx in test_list]# printing resultprint("The String List after extension : " + str(res)) |
The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS'] The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']
Method #2 : Using split() + join()
This is one of the way in which this task can be performed. In this, we perform the task of extension using join() and split().
Python3
# Python3 code to demonstrate working of# Split flatten String List# Using split() + join() # initializing listtest_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']# printing original listprint("The original list is : " + str(test_list))# Split flatten String List# Using split() + join()res = '-'.join(test_list).split('-')# printing resultprint("The String List after extension : " + str(res)) |
The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS'] The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']


