Python | Remove prefix strings from list

Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with specific prefix are removed. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + remove() + startswith()
The combination of above functions can solve this problem. In this, we remove the elements that start with particular prefix accessed using loop and return the modified list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Remove prefix strings from list
# using loop + remove() + startswith()
  
# initialize list 
test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize prefix 
pref = 'x'
  
# Remove prefix strings from list
# using loop + remove() + startswith()
for word in test_list[:]:
    if word.startswith(pref):
        test_list.remove(word)
  
# printing result
print("List after removal of Kth character of each string : " + str(test_list))

chevron_right


Output :

The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']

 

Method #2 : Using list comprehension + startswith()
This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the prefix.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Remove prefix strings from list
# using list comprehension + startswith()
  
# initialize list 
test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize prefix 
pref = 'x'
  
# Remove prefix strings from list
# using list comprehension + startswith()
res = [ele for ele in test_list if not ele.startswith(pref)]
  
# printing result
print("List after removal of Kth character of each string : " + str(res))

chevron_right


Output :

The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.