Reputation: 285
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']
Upvotes: 20
Views: 84889
Reputation: 76667
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)
Upvotes: 42
Reputation: 51
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)
Upvotes: 2
Reputation:
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.
Upvotes: 0
Reputation: 12212
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']
Upvotes: 1
Reputation: 2946
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.
Upvotes: 5
Reputation: 11
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.
Upvotes: 1
Reputation: 391854
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.
Upvotes: 13
Reputation: 14420
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
Upvotes: 14