How to Filter list elements starting with a given Prefix using Python?


The term prefix is defined by the beginning of the word or letter. In this article, we will learn how to use Python built-in functions like startswith(), filter(), lambda, and len() to Filter list elements starting with a given Prefix using Python.

Let’s take an example to understand this −

Let’s take an example to understand this:
Given element list, My_list = [“Amelia”,  “Kinshuk”,  “Rosy”,  “Aman”]
Keyword to be searched, Prefix = “Am”
Final result = [“Amelia”, “Aman”]

Syntax

The following syntax is used in all the examples −

startswith()

The is a built-in method in Python that returns true if the given condition is satisfied if the string starts with a specific value.

filter()

The filter() method is applied when we need to filter the items based on specific conditions. In simple terms, it allows users to iterate those elements that are extracted to satisfy the condition.

lambda

This lambda function in Python is known as an anonymous function. It can be used when function objects are required.

len()

This is a built-in method in Python that returns the length of the items present in an object.

Using List Comprehension

The program uses list comprehension with the help of a method named startswith() that can be used to filter the prefix element from the list.

Example

In the following example, we will use the list comprehension in the return statement of a function named prefix_list_element_filter() that will iterate the list value using for loop and check the prefix using startswith(). The togetherness of for loop and if-statement at one place is called list comprehension. Then create the list in the variable my_list. Moving ahead to set the calling function that passes the parameters- my_list( store the list values) and Am( prefix ) to work on filtration of list element starting element with a given prefix. Finally, we are printing the result with the help of the variable filter_list.

def prefix_list_element_filter(lst, prefix):
   return [item for item in lst if item.startswith(prefix)]

# Create the list
my_list = ["Amar", "Bunny", "Aman", "Ganesh", "Rajendra"]
filter_list = prefix_list_element_filter(my_list, "Am")
print("The given element start with prefix:", filter_list)

Output

 The given element start with prefix: ['Amar', 'Aman']

Using a for Loop

The program uses for loop to iterate the given list and check the prefix with startswith(). Then it will use an empty list that stores the filter prefix element by using a built-in method named append().

Example

In the following example, we will first start the program by defining the function with def keyword that accepts two parameters- lst(to receive the list values) and prefix(to receive the prefix keyword). Next, it will use the for loop to iterate into the list and then set the prefix using startswith() that accepts the parameter prefix( value receive from the function). Then use the method named append() that added the filter list element to the variable filtered_list and returns to get the result. Now create the list in the variable fruit_list. Then use the calling function to pass the parameters of list values and prefix in the variable filter_list. Finally, print the result with the help of a variable named filter_list.

def prefix_list_element_filter(lst, prefix):
   filtered_list = []
   for item in lst:
      if item.startswith(prefix):
         filtered_list.append(item)
   return filtered_list

# Create the list
fruit_list = ["apple", "banana", "avocado", "blue berry", "kiwi"]
filter_list = prefix_list_element_filter(fruit_list, "b")
print("The given element start with prefix:\n", filter_list)

Output

 The given element start with prefix:
 ['banana', 'blue berry']

Using Filter() Function

The program uses the filter() to identify the specific prefix and lambda to set the prefix using the method named startswith() which can be used to filter the specific prefix.

Example

In the following example, start using the functions with a def keyword that accepts two parameters- lst( to receive the list values) and prefix( to receive the specific keyword search) that will filter a list of items based on whether they start with a given prefix. This function returns the prefixed result by using some of the built-in functions like list(), filter(), lambda, and startswith(). Then create the list to store the value of strings in the variable course_list. Next, use the function call to pass the values- course_list and “bc” in the variable filter_list. Now use the print function that set the variable named filter_list to get the result.

def prefix_list_element_filter(lst, prefix):
   return list(filter(lambda item: item.startswith(prefix), lst))

# Create the list
course_list = ["dca", "bca", "bcom", "MCA", "pgdca"]
filter_list = prefix_list_element_filter(course_list, "bc")
print("The given element start with prefix:\n", filter_list)

Output

 The given element start with prefix:
 ['bca', 'bcom']

Using a List Comprehension With a Conditional Expression

The program uses a function that returns the list compression by setting some condition expression that can be used to filter the list element starting with a given prefix.

Example

In the following example, start using the function filter_list_elements_prefix() that accepts two parameters- lst( store the list) and prefix( receive the specific prefix during the function call). This function returns the new list by using list comprehension i.e. the expression item[:len(prefix)] takes a slice of each item in lst from the beginning to the length of the prefix and compares it to the prefix. If they are equal, the item is included in the new list. Next, create the list to store some string values in the variable my_list. Then initialize the variable filter_list that stores the same name as the function(above mentioned) to pass the value of the list and prefix. Finally, use the variable filter_list in the print function to get the result.

def filter_list_elements_prefix(lst, prefix):
   return [item for item in lst if item[:len(prefix)] == prefix]

# Create the list
my_list = ["tea", "coffee", "cheese", "teaspoon", "sugar"]
filter_list = filter_list_elements_prefix(my_list, "tea")
print("The given element start with prefix:\n", filter_list)

Output

 The given element start with prefix:
 ['tea', 'teaspoon']

Conclusion

We discussed the various ways to solve the problem statement that filter the element starting with a given prefix. There are some built-in functions like startswith(), append(), and len() that can be used to filter the prefix and return the result according to the given condition. This program relates real-life examples like a name list of multiple people to be searched by a specific prefix.

Updated on: 17-Jul-2023

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements