Plug4
Plug4

Reputation: 3938

Python: Issues with "if not any"

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.

Upvotes: 1

Views: 3535

Answers (2)

Ben
Ben

Reputation: 6777

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)]

Upvotes: 4

dan04
dan04

Reputation: 91161

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

Upvotes: 3

Related Questions