Skip to content
Related Articles

Related Articles

Python – Filter list elements starting with given Prefix
  • Last Updated : 30 Jun, 2020

Sometimes, we need to filter the list with the first character of each string in the list. This type of task has many applications in day-day programming and even in the competitive programming domain. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + startswith()
In this method, we use list comprehension for traversal logic and the startswith method to filter out all the strings that starts with a particular letter. The remaining strings can be used to make a different list.




# Python3 code to demonstrate
# Prefix Separation
# Using list comprehension + startswith()
  
# initializing list
test_list = ['sapple', 'orange', 'smango', 'grape']
  
# initializing start Prefix
start_letter = 's'
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + startswith()
# Prefix Separation
with_s = [x for x in test_list if x.startswith(start_letter)]
without_s = [x for x in test_list if x not in with_s]
  
# print result
print("The list without prefix s : " + str(without_s))
print("The list with prefix s : " + str(with_s))


Output :

The original list : ['sapple', 'orange', 'smango', 'grape']
The list without prefix s : ['orange', 'grape']
The list with prefix s : ['sapple', 'smango']

 

Method #2 : Using filter() + lambda + startswith()
This task can be performed using the filter function with performs the similar task internally as the above function and lambda is helper function to build the logic.






# Python3 code to demonstrate
# Prefix Separation
# Using filter() + startswith() + lambda
  
# initializing list
test_list = ['sapple', 'orange', 'smango', 'grape']
  
# initializing start Prefix
start_letter = 's'
  
# printing original list
print("The original list : " + str(test_list))
  
# using filter() + startswith() + lambda
# Prefix Separation
with_s = list(filter(lambda x: x.startswith(start_letter), test_list))
without_s = list(filter(lambda x: not x.startswith(start_letter), test_list))
  
# print result
print("The list without prefix s : " + str(without_s))
print("The list with prefix s : " + str(with_s))


Output :

The original list : ['sapple', 'orange', 'smango', 'grape']
The list without prefix s : ['orange', 'grape']
The list with prefix s : ['sapple', 'smango']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :