Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to convert output to list

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?

like image 761
ANURAG VERMA Avatar asked Dec 30 '22 17:12

ANURAG VERMA


2 Answers

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]
like image 143
Sanjeevan Khanduri Avatar answered Jan 02 '23 08:01

Sanjeevan Khanduri


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]
>>> 
like image 43
Daniel Hao Avatar answered Jan 02 '23 07:01

Daniel Hao