Python program to replace all Characters of a List except the given character

When it is required to replace all characters of a list except a given character, a list comprehension and the == operator are used. This technique allows you to preserve specific characters while replacing all others with a substitute character.

Using List Comprehension

The most Pythonic approach uses a conditional list comprehension to check each element ?

characters = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']

print("The list is:")
print(characters)

replace_char = '$'
retain_char = 'P'

result = [element if element == retain_char else replace_char for element in characters]

print("The result is:")
print(result)
The list is:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']
The result is:
['P', '$', '$', '$', '$', '$', 'P', '$', 'P']

Using a Regular Loop

You can also achieve the same result using a traditional for loop ?

characters = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']
replace_char = '$'
retain_char = 'P'

result = []
for element in characters:
    if element == retain_char:
        result.append(element)
    else:
        result.append(replace_char)

print("Original list:", characters)
print("Modified list:", result)
Original list: ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']
Modified list: ['P', '$', '$', '$', '$', '$', 'P', '$', 'P']

Using map() Function

The map() function with a lambda expression provides another approach ?

characters = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']
replace_char = '$'
retain_char = 'P'

result = list(map(lambda x: x if x == retain_char else replace_char, characters))

print("Original list:", characters)
print("Modified list:", result)
Original list: ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'H', 'P']
Modified list: ['P', '$', '$', '$', '$', '$', 'P', '$', 'P']

How It Works

  • The list comprehension iterates through each element in the original list

  • For each element, it checks if the element equals the character to retain

  • If the condition is true, the original element is kept

  • If the condition is false, the element is replaced with the substitute character

  • The result is a new list with selective character replacement

Conclusion

List comprehension provides the most concise solution for replacing characters selectively. Use map() with lambda for functional programming style, or traditional loops for better readability in complex scenarios.

Updated on: 2026-03-26T01:14:28+05:30

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements