Python Program to remove a specific digit from every element of the list
When it is required to remove specific digit from every element of the list, an iteration and ‘set’ operator and ‘str’ methods are used.
Below is a demonstration of the same
my_list = [123, 565, 1948, 334, 4598]
print("The list is :")
key = 3
print("The key is :")
my_result = 
for element in my_list:
if list(set(str(element))) == str(key) and len(set(str(element))) == 1:
my_result.append(int(''.join([element_1 for element_1 in str(element) if int(element_1) != key])))
print("The result is :")
The list is :
[123, 565, 1948, 334, 4598]
The key is :
The result is :
- A list of integers is defined and is displayed on the console.
- A value for key is defined and is displayed on the console.
- An empty list is created.
- The list is iterated over, and the element at zeroth index is checked to match the key after converting it to a string, and to a set, and then to a list.
- The ‘and’ operator is also used to check if the specific element’s length is equal to 1.
- If yes, an empty space is appended to the empty list.
- Otherwise, it is converted into a string by iterating over it using list comprehension.
- This is done only if the element is not equal to key.
- This is again converted to an integer and is appended to the empty list.
- This is displayed as output on the console.
Published on 16-Sep-2021 08:22:09