Program to return the given char and replace other elements with * using Python


In this section of python programming, our task is to print only the desired element from the list and replace all other elements with some special character (or you can give any other replace character also.)

Program to return the given char and replace other elements.


input_list = ['at', 'the', 'above', 'at', 'a', 'to']
find_string = 'at'
replace_string = '*'

# Using lambda
output1 = list(map(lambda i: find_string if i == find_string else replace_string, input_list))
print("Using lambda", str(output1))

# Using list comprehension
output = [i if i == find_string else replace_string for i in input_list]
print("Using list comprehension", str(output))



Program to return the given char and replace other elements Output


In the above code, we used two ways to find a char and replace other characters: 1. lambda function ; 2. list comprehension.

With lambda function we have used map() and list() also. The lambda function will check the condition whether the required char is there at index or not. If it is found the value is mapped as it is in the list else the value is replaced with replace_string and then stored in the output list.

Similarly in list comprehension, we are checking whether the required value is equal to the ith element of the list or else replacing the value with the replace_string for all elements in the given input_list.


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.