Python - Filter List that start with specific Prefix string
Python - Filter List items that start with specific Prefix string
To filter a list of strings that start with a specific prefix string in Python, you can use list comprehension, filter() built-in function, or use a simple For-loop.
In this tutorial, you will learn how to filter list of strings that start with a specific prefix string, with examples.
You may refer Python - Filter List tutorial, to get an idea of how to filter a list.
1. Filter list of strings that start with specific prefix using List Comprehension
In this example, we will take a list of strings in my_list, and filter the strings that start with a specific prefix string "Pe", using List Comprehension with If condition.
Python Program
my_list = ["Apple", "Pears", "Fig", "Peach", "Mango"]
filtered_list = [x for x in my_list if x.startswith("Pe")]
print(f"Filtered list : {filtered_list}")
Output
Filtered list : ['Pears', 'Peach']
Only the items that start with the prefix string "Pe"
made it to the filtered list.
2. Filter list of strings that start with specific prefix using filter() built-in function
In this example, we will filter the list of strings my_list that start with a specific prefix string "Pe", using filter() built-in function.
Python Program
my_list = ["Apple", "Pears", "Fig", "Peach", "Mango"]
filtered_list = filter(lambda x: x.startswith("Pe"), my_list)
print(f"Filtered list : {filtered_list}")
Output
Filtered list : ['Pears', 'Peach']
3. Filter list that start with specific prefix using For loop
In this example, we will use a simple For loop, and an if statement to filter the list of strings my_list that start with a specific prefix string "Pe".
Python Program
my_list = ["Apple", "Pears", "Fig", "Peach", "Mango"]
filtered_list = []
for x in my_list:
if x.startswith('Pe'):
filtered_list.append(x)
print(f"Filtered list : {filtered_list}")
Output
Filtered list : ['Pears', 'Peach']
Summary
Summarizing this tutorial on Python Lists, we have seen different ways to filter a list of strings starting with a specified prefix string in Python, with examples.