19

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']
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Jacky
  • 275
  • 1
  • 2
  • 6

8 Answers8

42

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)
gopi1410
  • 6,567
  • 9
  • 41
  • 75
Daniel Stutzbach
  • 74,198
  • 17
  • 88
  • 77
  • if you want to modify the list in-place rather than create a list, this can be done with simple loop. – tlayton Jul 01 '10 at 15:37
  • @mykhal Just checking, is that a joke? It does work on multi-digit numbers, of course – JAL Jul 01 '10 at 16:39
  • @razpetia: Fixed to handle negative numbers – Daniel Stutzbach Jul 01 '10 at 16:40
  • 1
    The generalizations make this much less clear. Try S. Lott's more Pythonic answer instead. – Seth Johnson Jul 01 '10 at 16:54
  • @Daniel Stutzbach: Your filtering function is great but you should've used filter(). Keep it pythonic, y'know .. – ktdrv Jul 01 '10 at 17:13
  • @Brian: It is not at clear to me that the original poster needs (or wants) to filter hexadecimal. – Daniel Stutzbach Jul 01 '10 at 20:15
  • @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 Jul 01 '10 at 20:45
  • This answer also won't handle ' 4' or '4 ' or the like. – Seth Johnson Jul 06 '10 at 13:03
  • Isn't there like any method for that in core Python? e.g. list.delete(obj_type)? – Kaszanas Aug 30 '20 at 16:55
  • The ALTERNATIVE results in an filter-object. Use list(no_integers) to get back an list-objekt. And it results in ONLY THE NUMBERS. To get the list without the numbers use: is_not_integer = lambda s: not s.isdigit() and not (s[0] == '-' and s[1:].isdigit()) – MichiBack Jan 04 '22 at 17:07
14

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

Gary Kerr
  • 13,650
  • 4
  • 48
  • 51
13

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
  • 384,516
  • 81
  • 508
  • 779
5

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
  • 2,836
  • 4
  • 29
  • 34
2

To remove all integers from the list

ls = ['1','introduction','to','molecular','8','the','learning','module','5']
ls_alpha = [i for i in ls if not i.isdigit()]
print(ls_alpha)
buddu
  • 51
  • 5
1

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.
  • 11
  • 2
  • 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) – Jochen Ritzel Jul 01 '10 at 16:23
1

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
  • 12,014
  • 3
  • 38
  • 57
0

You can use the filter built-in to get a filtered copy of a list.

>>> the_list = ['1','introduction','to','molecular',-8,'the','learning','module',5L]
>>> the_list = filter(lambda s: not str(s).lstrip('-').isdigit(), the_list)
>>> the_list
['introduction', 'to', 'molecular', 'the', 'learning', 'module']

The above can handle a variety of objects by using explicit type conversion. Since nearly every Python object can be legally converted to a string, here filter takes a str-converted copy for each member of the_list, and checks to see if the string (minus any leading '-' character) is a numerical digit. If it is, the member is excluded from the returned copy.

The built-in functions are very useful. They are each highly optimized for the tasks they're designed to handle, and they'll save you from reinventing solutions.