Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 16 Aug, 2022

Given a List that contains only string elements, the following program shows methods of 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 the 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']

Time Complexity: O(n) 
Auxiliary Space: O(1)

Method 2: Using list comprehension and join()

In this, we perform the task of recreating a 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']

Time Complexity: O(n) 
Auxiliary Space: O(1)

Method 3 : Using count() method.

Iterate over the given list of strings and find the count of the given character in each string and append it to the output list.

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 i in test_list:
    res.append(K*i.count(K))
# printing result
print("Modified List : " + str(res))

Output

The original list is : ['google', 'is', 'good', 'goggled', 'god']
Modified List : ['gg', '', 'g', 'ggg', 'g']

Time Complexity: O(n), as the count operator takes O(n)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!