[Tutor] Python program to remove a specific digit from every element of list

Manprit Singh manpritsinghece at gmail.com
Wed Apr 21 03:09:33 EDT 2021


Dear Sir,

Consider a list lst = [333, 435, 479, 293, 536], i have to remove digit 3
from each element from this list, Along with this if a number made by all 3
is present in the list, that number has to be completely removed . the
answer for list lst must be :

[45, 479, 29, 56]

The way i have solved it, is given below :

def remove_digit(x, n):
    """Function that removes digit n from a number x """
    ans, i = 0, 0
    while x != 0:
        x, rem = divmod(x, 10)
        if rem != n:
            ans = ans + (rem * 10**i)
            i = i + 1
    return ans

lst = [333, 435, 479, 293, 536]
ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)]

print(ans) gives the desired answer as given above.Just need to know if

Is there any better implementation for this problem ? assignment

expression can be used in the list comprehension written above ?

Regards

Manprit Singh


More information about the Tutor mailing list