Python | Remove string prefix from list

Method # 1: Using loop + remove () + startswith ()
Combining the above functions can solve this problem. In this, we remove elements that start with a specific prefix, available using a loop, and return the modified list.

# Python3 demo code
# Remove prefix lines from the list
# using loop + remove () + starts with ()

 
# initialize the list

test_list = [ `xall` , `xlove` , ` gfg` , `xit` , `is` , `best` ]

  
# print original list

print ( "The original list:" + str (test_list))

  
# initialize prefix

pref = `x`

 
# Remove prefix strings from the list
# using loop + delete () + starts with ()

for word in test_list [:]:

if word.startswith (pref):

test_list.remove (word)

  
# print result

print ( "List after removal of Kth character of each string:" + str (test_list))

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 the comprehension list + startswith()
This is another a way to accomplish this task. However, we are not doing in-place deletion, instead we are re-creating the list with no elements matching the prefix.

# Python3 code to demonstrate how it works
# Remove prefix lines from the list
# use comprehension list + startwith ()

 
# initialize the list

test_list = [ `xall` , ` xlove` , `gfg` , `xit` , ` is` , `be st` ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# initialize prefix

pref = `x`

 
# Remove prefix strings from the list
# use comprehension list + startwith ( )

res = [ele for ele in test_list if not ele.startswith (pref )]

 
# print result

print ( "List after removal of Kth character of each string:" + str (res))

Output:

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