How to create a function that takes a list of non-negative integers and strings and return a new list without the strings?
Eg. filter_list([1, 2, "a", "b"])
➞ [1, 2]
Issue: Not able to convert output to list
def filter_list(a):
mylist=[]
if type(a)==list:
for i in a:
if type(i)==int:
output=print(i)
mylist+=output
return mylist
What am I doing wrong?
The mistake you made is that you are assigning the value returned by print()
to output
(which is None
) and then you are adding a None
type object to a list
object which is an invalid operation. You can fix your code by doing something like this :
def filter_list(a):
mylist=[]
if type(a)==list:
for i in a:
if type(i)==int:
print(i)
mylist+=[i]
return mylist
However this can be done in a much prettier way using List comprehensions!
List comprehension is a way to create a new list using a relatively much shorter syntax.
[elem for elem in _list if type(elem) is int]
Can this help:
>>> def filter_list(lst):
return [item for item in lst if type(item) is not str]
>>> filter_list([1, 2, 'a', 'b'])
[1, 2]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With