Create List of Substrings from List of Strings in Python
Last Updated :
23 Feb, 2024
In Python, when we work with lists of words or phrases, we often need to break them into smaller pieces, called substrings. A substring is a contiguous sequence of characters within a string. Creating a new list of substrings from a list of strings can be a common task in various applications. In this article, we will create a new list of substrings from a list of strings.
Create a New List of Substrings from the List of Strings
Below are some of the ways by which we can create a new list of substrings from the list of strings in Python:
Using List Comprehension
In this example, a list comprehension is employed to create a new list, `substring_list`, containing substrings extracted from each string in the `original_list`. The slicing notation `[s[1:4] for s in original_list]` extracts characters from index 1 to 3 (exclusive) from each string in the original list.
Python3
original_list = [ "apple" , "banana" , "orange" ]
substring_list = [s[ 1 : 4 ] for s in original_list]
print (substring_list)
|
Output
['ppl', 'ana', 'ran']
Using map() Function
In this example, a function `extract_substring` is defined to extract a substring from a given string `s`, and the `map()` function is used to apply this function to each element in the `original_list`. The result is a new list, `substring_list`, containing the extracted substrings, which is then printed.
Python
original_list = [ "apple" , "banana" , "orange" ]
def extract_substring(s):
return s[ 1 : 4 ]
substring_list = list ( map (extract_substring, original_list))
print (substring_list)
|
Output
['ppl', 'ana', 'ran']
Using Lambda Function with map() Function
In this example, a lambda function is applied using the `map()` function to extract substrings `[1:4]` from each string in the `original_list`. The result is a new list, `substring_list`, containing the extracted substrings, which is then printed.
Python
original_list = [ "apple" , "banana" , "orange" ]
substring_list = list ( map ( lambda s: s[ 1 : 4 ], original_list))
print (substring_list)
|
Output
['ppl', 'ana', 'ran']
Using List Comprehension with Conditional Statements
In this example, a list comprehension with a conditional statement is employed to create a new list, `substring_list`. It extracts substrings `[1:4]` from strings in the `original_list` only if the length of the string is greater than or equal to 4; otherwise, the original string is retained. The resulting list is then printed.
Python
original_list = [ "apple" , "banana" , "orange" ]
substring_list = [s[ 1 : 4 ] if len (s) > = 4 else s for s in original_list]
print (substring_list)
|
Output
['ppl', 'ana', 'ran']
Share your thoughts in the comments
Please Login to comment...