Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to remove a specific digit from every element of the list
When you need to remove a specific digit from every element of a list, you can use string manipulation with list comprehension and filtering techniques.
Example
Below is a demonstration of removing digit 3 from all list elements ?
numbers = [123, 565, 1948, 334, 4598]
print("The list is:")
print(numbers)
digit_to_remove = 3
print("The digit to remove is:")
print(digit_to_remove)
result = []
for element in numbers:
# Convert to string and filter out the specific digit
filtered_digits = ''.join([digit for digit in str(element) if int(digit) != digit_to_remove])
# If all digits were removed, append empty string or 0
if filtered_digits == '':
result.append('')
else:
result.append(int(filtered_digits))
print("The result is:")
print(result)
The list is: [123, 565, 1948, 334, 4598] The digit to remove is: 3 The result is: [12, 565, 1948, 4, 4598]
Using List Comprehension
A more concise approach using list comprehension ?
numbers = [123, 565, 1948, 334, 4598]
digit_to_remove = 3
result = [
int(''.join([d for d in str(num) if int(d) != digit_to_remove]))
if ''.join([d for d in str(num) if int(d) != digit_to_remove]) != ''
else 0
for num in numbers
]
print("Original list:", numbers)
print("After removing digit", digit_to_remove, ":", result)
Original list: [123, 565, 1948, 334, 4598] After removing digit 3 : [12, 565, 1948, 4, 4598]
Handling Edge Cases
When all digits in a number are the target digit (like 333), you need to handle this case ?
numbers = [123, 333, 1948, 334, 4598]
digit_to_remove = 3
result = []
for num in numbers:
# Remove the target digit
filtered = ''.join([d for d in str(num) if int(d) != digit_to_remove])
# Handle case where all digits were removed
if filtered == '':
result.append(0) # or use None, or skip entirely
else:
result.append(int(filtered))
print("Original:", numbers)
print("Result: ", result)
Original: [123, 333, 1948, 334, 4598] Result: [12, 0, 1948, 4, 4598]
How It Works
- String conversion: Convert each number to string to access individual digits
- Filtering: Use list comprehension to keep only digits that don't match the target
- Rejoining: Join filtered digits back into a string
- Type conversion: Convert back to integer if result is not empty
Conclusion
Use string manipulation with list comprehension to remove specific digits from numbers. Handle edge cases where all digits are removed by returning 0 or an appropriate default value.
Advertisements
