Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all integer values from a list in python

Tags:

python

string

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']
like image 736
Jacky Avatar asked Jul 01 '10 15:07

Jacky


2 Answers

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)
like image 79
Daniel Stutzbach Avatar answered Sep 28 '22 15:09

Daniel Stutzbach


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.

like image 33
S.Lott Avatar answered Sep 28 '22 16:09

S.Lott