Reputation: 3938
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
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