0

I try to write a function that would eliminate string elements from the list and return the new list.

My solution is:

def foo(lst):
    for i in lst:
        if type(i) == str:
           lst.remove(i)

    print(lst)
    return(lst) 


Whereas the correct one is:

def foo(lst):
    return [i for i in lst if not isinstance(i, str)]

Is not logic basically the same? Where is my mistake? Is some lists my code works, for some does not

  • 2
    No, the logic isn't the same, and the entire approach is different. In the first case, you are attempting to modify the list that was passed in, and in doing so, fell into the classic trap. You then return the same list object. In the second one, you create *a new list* and return that new list. – juanpa.arrivillaga Apr 28 '20 at 23:39
  • @ggorlen what do you mean with regards to `type(str)`? how is that relevant? This is not an idiomatic way of checking the type of an object, but it still works. – juanpa.arrivillaga Apr 28 '20 at 23:40
  • `list.remove` is going to modify the original `list` object in the outer scope which who ever gave you this problem may not want you to do. the list comp method is going to give you a completely new `list` object without changing the original one. – Phillyclause89 Apr 28 '20 at 23:40
  • Please see [this question](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) for a good explanation of why modifying a list while you iterate through it will lead to unexpected results. This should probably be closed as a duplicate of that question – juanpa.arrivillaga Apr 28 '20 at 23:43
  • @juanpa.arrivillaga You're right. I figured they were comparing against a builtin function but I guess it's a type as well. Then the only issue is modifying a list while iterating over it, so it's a clear dupe. – ggorlen Apr 28 '20 at 23:45
  • [Step thru it](http://pythontutor.com/visualize.html#code=def%20f1%28lst%29%3A%0A%20%20%20%20for%20i%20in%20lst%3A%0A%20%20%20%20%20%20%20%20if%20type%28i%29%20%3D%3D%20str%3A%0A%20%20%20%20%20%20%20%20%20%20%20lst.remove%28i%29%0A%20%20%20%20return%20lst%20%0Adef%20f2%28lst%29%3A%0A%20%20%20%20return%20%5Bi%20for%20i%20in%20lst%20if%20not%20isinstance%28i,%20str%29%5D%0Al%20%3D%20%5B1,2,3,'Str',4,'Str'%5D%0Aprint%28f2%28l%29%29%0Aprint%28f1%28l%29%29&cumulative=true&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=py3anaconda&rawInputLstJSON=%5B%5D&textReferences=false) – Phillyclause89 Apr 28 '20 at 23:45
  • Does this answer your question? [strange result when removing item from a list](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – ggorlen Apr 28 '20 at 23:46

0 Answers0