How to remove all rows from a list

my question is how to remove all the lines from the list, for example, if I have list=['hello',1,2,3,4,'goodbye','help'] , and the result will be list=[1,2,3,4]

+5
source share
3 answers

You need to use isinstance to filter out those elements that are strings. Also do not name your variable list , it obscures the built-in list

 >>> from numbers import Real >>> lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help'] >>> [element for element in lst if isinstance(element, Real)] [1, 2, 3, 4] 

or

 >>> [element for element in lst if isinstance(element, int)] [1, 2, 3, 4] 

or

 >>> [element for element in lst if not isinstance(element, str)] [1, 2, 3, 4] 
+9
source

You can do this with isinstance , but unlike another answer from user3100115 I would use blacklists that you don't need, not just a whitelist. Not sure what would be more appropriate for your special occasion, just adding this as an alternative. It also works without import.

 lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help'] filtered = [element for element in lst if not isinstance(element, str)] print(filtered) # [1, 2, 3, 4] 

Instead of understanding the list, you can also use the built-in filter . This returns the generator, so to print it directly, you must first convert it to a list. But if you are going to iterate over it (for example, using for -loop), do not convert it, and it will be faster and consume less memory due to the "lazy evaluation". You can achieve the same as in the example above if you replace the square brackets with parentheses.

 lst = ['hello', 1, 2, 3, 4, 'goodbye', 'help'] filtered = list(filter(lambda element: not isinstance(element, str), lst)) print(filtered) # [1, 2, 3, 4] 
+2
source

Either use the list as @ user3100115 or use the "lisp / lambda approach"

 >> l = [1, 2, 'a', 'b'] >> list(filter(lambda a: isinstance(a, int), l)) [1, 2] 

By the way, do not name the variable list . This is already a python function. :)

+1
source

All Articles