Open In App

Python | Split flatten String List

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. Let’s 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 list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
 
# printing original list
print("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 result
print("The String List after extension : " + str(res))


Output

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']

Time Complexity: O(n) where n is the total number of values in the list “test_list”. 
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.

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 list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Split flatten String List
# Using split() + join()
res = '-'.join(test_list).split('-')
 
# printing result
print("The String List after extension : " + str(res))


Output

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']

Time Complexity: O(n), where n is the length of the input list. This is because we’re using the split() + join() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #3: Using itertools.chain.from_iterable

Python3




# Using itertools.chain.from_iterable
 
import itertools
 
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
 
print("The original list is : " + str(test_list))
 
res = list(itertools.chain.from_iterable(
    map(lambda x: x.split('-'), test_list)))
 
print("The String List after extension : " + str(res))


Output

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']

Time Complexity: O(n), where n is the total number of characters in all strings.
Auxiliary Space: O(n), since we are storing the result in a list.

Method #4: Using the reduce function from the functools library

Python3




import functools
 
# initialize a list of strings
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
print("The original list is : " + str(test_list))
# use the reduce function from the functools library to flatten the list of strings
res = functools.reduce(lambda x, y: x + y.split("-"), test_list, [])
 
# print the result
print(res)
# this code is contributed by Asif_Shaik


Output

The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using the str.replace() method: 

A list of strings and extracts individual words from them, combining all of the words into a single list. It does so by initializing an empty list called words, iterating over each string in the original list, removing any hyphens from the string, and then splitting it into individual words using the split() function. The resulting words are then added to the words list using the extend() method, which concatenates two lists.

In essence, this code is designed to extract individual words from a list of strings, and produce a new list that contains all of the words from the original list. It does this by first removing hyphens from the strings, and then using the split() function to extract individual words from each string. Finally, the code concatenates all of the resulting lists of words into a single list, which it outputs.

Python3




test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
# create an empty list to hold the words
words = []
# printing original list
print("The original list is : " + str(test_list))
 
# iterate over each string in the list
for string in test_list:
    # remove any hyphens in the string and split it into words
    words_in_string = string.replace('-', ' ').split()
    # add the words to the list of words
    words.extend(words_in_string)
print("The String List after extension : " + str(words))
# This code is contributed by Jyothi pinjala


Output

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']

Time Complexity: O(n)
Auxiliary  Space: O(n)

Method 6: Using nested for loops:

Step-by-step approach:

  1. Initialize the list test_list.
  2. Print the original list using the print() function.
  3. Initialize an empty list res to store the flattened list.
  4. Use nested for loops to iterate over each string in test_list, and then iterate over each word in the string by calling the split(‘-‘) method.
  5. Append each word to the res list.
  6. Print the flattened list using the print() function.

Python3




# Python3 code to demonstrate working of
# Split flatten String List
# Using nested for loops
     
# initializing list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Split flatten String List
# Using nested for loops
res = []
for string in test_list:
    for word in string.split('-'):
        res.append(word)
 
# printing result
print("The String List after extension : " + str(res))


Output

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']

Time complexity: O(n*m), where n is the length of the test_list and m is the maximum number of words in a string.
Auxiliary space: O(n*m), where n is the length of the test_list and m is the maximum number of words in a string, as we need to store all the words in the flattened list.

Method 7: Using reduce(), split(), and operator.concat

In this method, reduce() function, the concat() function is applied to each element of the input list after splitting the string using the split() method. The resulting list of split strings is then flattened into a single list. Then result is printed using the print() function.

Python3




from functools import reduce
import operator
 
# initializing list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
 
# printing original list
print("The original list is: " + str(test_list))
 
# Split flatten String List
# Using reduce() + split() + operator.concat
res = reduce(operator.concat, [sub.split('-') for sub in test_list])
 
# printing result
print("The String List after extension: " + str(res))


Output

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']

Time Complexity: O(n), where n is the total number of characters in all strings in the input list.
Auxiliary  Space: O(n), since the output list contains all the characters from the input strings.



Previous Article
Next Article

Similar Reads

Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Pandas Split strings into two List/Columns using str.split()
Pandas provide a method to split string around a passed separator/delimiter. After that, the string can be stored as a list in a series or it can also be used to create multiple column data frames from a single separated string. It works similarly to Python's default split() method but it can only be applied to an individual string. Pandas <code
4 min read
Python | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print (
5 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its value in dictionary. Input : test_list = ["Gfg", "
4 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list c
7 min read
Practice Tags :
three90RightbarBannerImg