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.

Example

Below is a demonstration of the same

my_list = [123, 565, 1948, 334, 4598]

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

key = 3
print("The key is :")
print(key)

my_result = []

for element in my_list:
   if list(set(str(element)))[0] == str(key) and len(set(str(element))) == 1:
      my_result.append('')
   else:
      my_result.append(int(''.join([element_1 for element_1 in str(element) if int(element_1) != key])))

print("The result is :")
print(my_result)

Output

The list is :
[123, 565, 1948, 334, 4598]
The key is :
3
The result is :
[4598]

Explanation

  • 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.
Updated on: 2021-09-16T08:22:09+05:30

536 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements