-1

I've written this code for removing characters from a string. I used the filter function but it returns the same list without modification.

a = "Hello !!!!,  . / "
a1 = list(a)


def it(at):
    k = at.copy()
    charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]
    for x in charlist:
        filter(lambda t: t != x, k)
    print(k)


it(a1)

I've referred to this answer on Stack Overflow

2 Answers2

3

filter returns the filtered iterable; it doesn't modify it in place.

>>> def it(at):
...     charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]
...     print(list(filter(lambda t: t not in charlist, at)))
...
>>> it(a1)
['H', 'e', 'l', 'l', 'o']

An implementation closer to your original code would be to filter in a loop the way you were doing, but to reassign k each time:

>>> def it(at):
...     k = at.copy()
...     charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]
...     for x in charlist:
...         k = list(filter(lambda t: t != x, k))
...     print(k)
...
>>> it(a1)
['H', 'e', 'l', 'l', 'o']
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • How can I perform the same operation using slicing instead of a for loop? Something like : z = list(filter(lambda t: t != charlist[::], k)) – Sirius Black Jul 08 '20 at 06:51
  • Look at the first part of my answer for how to do this without a for loop (it doesn't involve slicing). – Samwise Jul 08 '20 at 13:56
0

Filter method returns an iterator that is already filtered. Refer to below code

a = "Hello !!!!,  . / "
a1 = list(a)


def it(at):
    k = at.copy()
    charlist = [",", ".", "/", " ", ":", ";", "\'", "\"", "!"]
    new_k = None
    for x in charlist:
        new_k = filter(lambda t: t != x, k)
    for s in new_k:
        print(s)


it(a1)
Yash Chauhan
  • 90
  • 3
  • 8
  • How can I perform the same operation using slicing instead of a for loop? Something like : z = list(filter(lambda t: t != charlist[::], k)) – Sirius Black Jul 08 '20 at 08:19