Open In App

Extract Substrings From A List Into A List In Python

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python is renowned for its simplicity and versatility, making it a popular choice for various programming tasks. When working with lists, one common requirement is to extract substrings from the elements of the list and organize them into a new list. In this article, we will see how we can extract substrings from a list into a list in Python.

Extract Substrings from a List into a List in Python

Below are some of the examples by which we can extract substrings from a list into a list in Python:

Example 1: Using List Comprehension

List comprehension is a concise and elegant way to create lists in Python. It also proves to be effective for extracting substrings from a list. This approach utilizes a compact syntax to iterate through the elements of the original_list and extracts the first three characters from each string. The resulting substring_list contains the desired substrings.

Python3




# Original List
original_list = ["apple", "banana", "cherry"]
 
# Extracting substrings using list comprehension
substring_list = [fruit[:3] for fruit in original_list]
 
# Displaying the results
print("Original List:", original_list)
print("Substring List:", substring_list)


Output

Original List: ['apple', 'banana', 'cherry']
Substring List: ['app', 'ban', 'che']

Example 2: Using Map and Lambda Function

This approach allows for more flexibility and customization in substring extraction. Here, the map function applies the lambda() function to each element of original_list, extracting the first three characters. The resulting substring_list is then converted to a list for better readability.

Python3




# Original List
original_list = ["python", "java", "csharp"]
 
# Extracting substrings using map and lambda
substring_list = list(map(lambda lang: lang[:3], original_list))
 
# Displaying the results
print("Original List:", original_list)
print("Substring List:", substring_list)


Output

Original List: ['python', 'java', 'csharp']
Substring List: ['pyt', 'jav', 'csh']

Conclusion

This article has explored the fundamental concepts of lists, substring extraction, and slicing in Python. Through practical examples and step-by-step guidance, you should now be equipped to confidently extract substrings from lists in your Python projects. Whether you’re working with textual data or any other type of sequence, the ability to manipulate substrings is a valuable skill in your programming toolkit.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads