Skip to content
Related Articles

Related Articles

Improve Article

Python Program to Removes Every Element From A String List Except For a Specified letter

  • Last Updated : 01 Nov, 2020

Given a List that contains only string elements, the following program shows methods how every other alphabet can be removed from elements except for a specific one and then returns the output.

Input : test_list = [“google”, “is”, “good”, “goggled”, “god”], K = ‘g’ 
Output : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’] 
Explanation : All characters other than “g” removed.
Input : test_list = [“google”, “is”, “good”, “goggled”, “god”], K = ‘o’ 
Output : [‘oo’, ”, ‘oo’, ‘o’, ‘o’] 
Explanation : All characters other than “o” removed. 

Method 1 : Using loop

In this, we remake the string, by appending only K, and avoiding all other strings from result.

Python3






# initializing list
test_list = ["google", "is", "good", "goggled", "god"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 'g'
  
res = []
for sub in test_list:
  
    # joining only K characters
    res.append(''.join([ele for ele in sub if ele == K]))
  
# printing result
print("Modified List : " + str(res))

Output:

The original list is : [‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]

Modified List : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’]

Method 2 : Using list comprehension and join()

In this, we perform the task of recreating list using list comprehension and then join() can concatenate all occurrences of K.

Python3




# initializing list
test_list = ["google", "is", "good", "goggled", "god"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 'g'
  
# appending and joining using list comprehension and join()
res = [''.join([ele for ele in sub if ele == K]) for sub in test_list]
  
# printing result
print("Modified List : " + str(res))

 Output:

The original list is : [‘google’, ‘is’, ‘good’, ‘goggled’, ‘god’]

Modified List : [‘gg’, ”, ‘g’, ‘ggg’, ‘g’]

 

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :