tags:

views:

221

answers:

6

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']
+11  A: 

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 (x[0] == '-' and x[1:].isdigit())
no_integers = filter(is_integer, mylist)
Daniel Stutzbach
if you want to modify the list in-place rather than create a list, this can be done with simple loop.
tlayton
Is the number is negative isdigit() won't work.
razpeitia
@mykhal Just checking, is that a joke? It does work on multi-digit numbers, of course
Alex JL
@razpetia: Fixed to handle negative numbers
Daniel Stutzbach
The generalizations make this much less clear. Try S. Lott's more Pythonic answer instead.
Seth Johnson
@Daniel Stutzbach: Your filtering function is great but you should've used filter(). Keep it pythonic, y'know ..
kaloyan
This won't work for hexadecimal.
Brian
@Brian: It is not at clear to me that the original poster needs (or wants) to filter hexadecimal.
Daniel Stutzbach
@Daniel: True, but if you're going to complain about not handling negative numbers, you can complain about this, too. It also doesn't handle '+5'.
Brian
This answer also won't handle ' 4' or '4 ' or the like.
Seth Johnson
+5  A: 

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

PreludeAndFugue
+9  A: 

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.

S.Lott
Why is `int` better than `str.isdigit`, though?
Daniel Stutzbach
As others have pointed out, `'-2'.isdigit()` will return `False`.
Seth Johnson
+1. See http://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python for discussion (with `float`, but still just as relevant).
Brian
A: 

Please do not use this way to remove items from a list: (edited after comment by THC4k)

>>> li = ['1','introduction','to','molecular','8','the','learning','module','5']
>>> for item in li:
        if item.isdigit():
            li.remove(item)

>>> print li
['introduction', 'to', 'molecular', 'the', 'learning', 'module']

This will not work since changing a list while iterating over it will confuse the for-loop. Also, item.isdigit() will not work if the item is a string containing a negative integer, as noted by razpeitia.

FT.
Python really needs a mechanism to prevent people from doing this. It looks like it would work, but it doesnt -- try with `li = ['iterating + removing -> skipping', '4', '5', 'see?']` (deleting 4 will skip the 5, so it remains in the list)
THC4k
+1  A: 

You can also use lambdas (and, obviously, recursion), to achieve that (Python 3 needed):

 isNumber = lambda s: False if ( not( s[0].isdigit() ) and s[0]!='+' and s[0]!='-' ) else isNumberBody( s[ 1:] )

 isNumberBody = lambda s: True if len( s ) == 0 else ( False if ( not( s[0].isdigit() ) and s[0]!='.' ) else isNumberBody( s[ 1:] ) )

 removeNumbers = lambda s: [] if len( s ) == 0 else ( ( [s[0]] + removeNumbers(s[1:]) ) if ( not( isInteger( s[0] ) ) ) else [] + removeNumbers( s[ 1:] ) )

 l = removeNumbers(["hello", "-1", "2", "world", "+23.45"])
 print( l )

Result (displayed from 'l') will be: ['hello', 'world']

Baltasarq
This doesn't work with negative numbers.
Alex JL
Well, yes, but it would be trivial to change that code to achieve that behaviour.
Baltasarq
Done, now it handles negative numbers.
Baltasarq
+3  A: 

I personally like filter. I think it can help keep code readable and conceptually simple if used in a judicious way:

x = ['1','introduction','to','molecular','8','the','learning','module','5'] 
x = filter(lambda i: not str.isdigit(i), x)

or

from itertools import ifilterfalse
x = ifilterfalse(str.isdigit, x)

Note the second returns an iterator.

twneale