Reputation: 55
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?
Upvotes: 4
Views: 826
Reputation: 2812
You could use a list comprehension which only includes list elements if they have the int
type.
def filter_list(lis):
return [i for i in lis if type(i) == int]
print(filter_list([1, 2, "a", "b"]))
Code Output:
[1, 2]
Upvotes: 2
Reputation: 453
You can use the filter method as follows:
def filter_list(a):
return list(filter(lambda x: type(x) == int, a))
print(filter_list([1, 2, "a", "b"]))
Output:
[1, 2]
Your code fixed:
def filter_list(a):
mylist=[]
for i in a:
if type(i)==int:
mylist.append(i)
return mylist
def filter_list1(a):
return list(filter(lambda x: type(x) == int, a))
print(filter_list([1, 2, "a", "b"]), filter_list1([1, 2, "a", "b"]))
Output:
[1, 2] [1, 2]
Upvotes: 1
Reputation: 304
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]
Upvotes: 2
Reputation: 8564
Use the filter
function itself:
>>> list(filter(lambda x: isinstance(x, int), [1, 2, "a", "b"]))
[1, 2]
Issue with your code is that instead of printing and using +=
(which is used to concatenate two lists, not one list
and one int
) to add to your list, you should append the element like this:
for i in a:
if type(i) == int:
mylist.append(i)
Upvotes: 1
Reputation: 12347
Use isinstance
and list comprehension:
def filter_list(lst):
return [i for i in lst if isinstance(i, int)]
Upvotes: 1
Reputation: 4980
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]
>>>
Upvotes: 2