Python: Issues with "if not any"

3.4k Views Asked by At

I have a problem with the Python function any(). I want to use the any() function to remove from a list any items that contains a digit. For instance:

lst = ['abc123','qwerty','123','hello']

and I apply the following code to remove from lst the items: 'abc123','123'

new_list = [item for item in lst if not any(item.isdigit() for char in item)]

I want new_list to contain only the items ['qwerty','hello'] but it turns out that new_list=lst...there is no change. Why? I also tried using import __builtin__ and __builtin__.any and no luck. I use Python 2.7.

2

There are 2 best solutions below

1
On BEST ANSWER

You ned to check against char, not item, inside your any:

new_list = [item for item in lst if not any(char.isdigit() for char in item)]

Alternatively, you can use the re regex module:

new_list = [item for item in lst if not re.search(r'\d', item)]
0
On

item.isdigit() should be char.isdigit().