Write a Python program to Replace all Characters of a List Except the given character


This program is written in Python and it performs the following operations:

  • It creates a list of characters named "val" containing 6 elements.
  • It prints the original list "val".
  • It creates a new list named "res".
  • The new list is created using a list comprehension which iterates over each character in the list "val".
  • For each character in the list "val", if it is equal to "T", it is appended to "res", otherwise it is replaced with "@" and then appended to "res".
  • Finally, it prints the final list "res".

Source Code

val = ['P', 'Y', 'T', 'H', 'O', 'N']
print("The original list : " + str(val))
 
res = [i if i == 'T' else '@' for i in val]
print("List after replacement : " + str(res))

Output

The original list : ['P', 'Y', 'T', 'H', 'O', 'N']
List after replacement : ['@', '@', 'T', '@', '@', '@']

Example Programs