I am just a beginner in python and I want to know is it possible to remove all the integer values from a list? For example the document goes like
['1','introduction','to','molecular','8','the','learning','module','5']
After the removal I want the document to look like:
['introduction','to','molecular','the','learning','module']
To remove all integers, do this:
no_integers = [x for x in mylist if not isinstance(x, int)]
However, your example list does not actually contain integers. It contains only strings, some of which are composed only of digits. To filter those out, do the following:
no_integers = [x for x in mylist if not (x.isdigit()
or x[0] == '-' and x[1:].isdigit())]
Alternately:
is_integer = lambda s: s.isdigit() or (s[0] == '-' and s[1:].isdigit())
no_integers = filter(is_integer, mylist)
You can do this, too:
def int_filter( someList ):
for v in someList:
try:
int(v)
continue # Skip these
except ValueError:
yield v # Keep these
list( int_filter( items ))
Why? Because int
is better than trying to write rules or regular expressions to recognize string values that encode an integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With