Home > Blockchain >  Python : Create a function that takes a list of integers and strings and returns a new list with the
Python : Create a function that takes a list of integers and strings and returns a new list with the

Time:03-02

I am new to coding in Python and I am struggling with a very simple problem. There is the same question but for javascript on the forum but it does not help me. My code is :

def filter_list(l):  
    for i in l:  
        if i != str():  
            l.append(i)  
        i = i   1  
    return(l)  

print(filter_list([1,2,'a','b']))

If you can help!

thanks

CodePudding user response:

Before I present solution here are some problems you need to understand.

str()

str() creates a new instance of the string class. Comparing it to an object with == will only be true if that object is the same string.

print(1 == str())
>>> False
print("some str" == str())
>>> False
print('' == str())
>>> True

iterators (no 1)

You have i = i 1 in your loop. This doesn't make any sense. i comes from for i in l meaning i looping over the members of list l. There's no guarantee you can add 1 to it. On the next loop i will have a new value

l = [1,2,'a']
for i in l:
    print(i)
>>> 1
>>> 2
>>> 'a'

To filter you need a new list

You are appending to l when you find a string. This means that when your loop finds an integer it will append it to the end of the list. And later it will find that integer on another loop interation. And append it to the end AGAIN. And find it in the next iteration.... Forever.

Try it out! See the infinite loop for yourself.

def filter_list(l):
     for i in l:
         print(i)
         if type(i) != str:
             l.append(i)
     return(l)

filter_list([1,2,'a','b'])

Fix 1: Fix the type check

def filter_list(l):  
    for i in l:  
        if type(i) != str:  
            l.append(i)  
    return(l)  

print(filter_list([1,2,'a','b']))

This infinite loops as discussed above

Fix 2: Create a new output array to push to

def filter_list(l):  
    output = []
    for i in l:  
        if type(i) != str:  
            output.append(i)  
    return output

print(filter_list([1,2,'a','b']))
>>> [1,2]

There we go.

Fix 3: Do it in idiomatic python

Let's use a list comprehension

l = [1,2,'a','b']
output = [x for x in l if type(x) != str]
print(output)
>>> [1, 2]

A list comprehension returns the left most expression x for every element in list l provided the expression on the right (type(x) != str) is true.

  • Related