How to remove all integer values from a list in python

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.


None of the items in your list are integers. They are strings which contain only digits. So you can use the isdigit string method to filter out these items.

items = ['1','introduction','to','molecular','8','the','learning','module','5']

new_items = [item for item in items if not item.isdigit()]

print new_items

Link to documentation: http://docs.python.org/library/stdtypes.html#str.isdigit

Tags:

Python

String