Home>

for example eats codelist= [12,3,1, '', 99,7,120]how to remove empty element?

lst= [i for i in lst if i!= '']

entithat2021-11-17 13:24:08

Mr. @entithat, I would like to point out that your version will not change the original list. A new one will be created.

A_Vaclav2021-11-17 13:30:47

@A_Vaclav, well, it's good, why lose data, albeit empty

entithat2021-11-17 13:32:39

@entithat All found elements will be deleted as well, not just one ...

A_Vaclav2021-11-17 14:12:19

@A_Vaclav, well, here it is already necessary to clarify)

entithat2021-11-17 14:58:23
  • Answer # 1

    list.remove (x) -Removes the first item in the list that has an x ​​value. ValueError if no such element exists. Reference.

    def remove_in_list (arr, template):
        try:
            res= arr [::] # we will not mutate the input data
            res.remove (template)
        except ValueError:
            #Pass
            print ('The item is not in the list')
            res= arr
        return res
    # Let's check how it works
    arr= [12,3,1, '', 99,7,120]
    arr= remove_in_list (arr, '')
    print (arr)
    arr= remove_in_list (arr, '')
    print (arr)
    

    Prints:

    [12, 3, 1, 99, 7, 120]
    The item is not in the list.
    [12, 3, 1, 99, 7, 120]
    

    And an option without try ... except, for "beginners":

    def remove_in_list_not_try (arr, template):
        if template in arr:
            res= arr [::] # we will not mutate the input data
            res.remove (template)
        else:
            #Pass
            print ('The item is not in the list')
            res= arr
        return res
    # Let's check how it works
    arr= [12,3,1, '', 99,7,120]
    arr= remove_in_list_not_try (arr, '')
    print (arr)
    arr= remove_in_list_not_try (arr, '')
    print (arr)
    
  • Answer # 2

    As an option, if you need to delete at once empty strings, and zeros, and empty collections, and valuesFalse, in general, everything is "empty" in one fell swoop:

    lst= [12,3,1, '', 99,7,120]
    print (list (filter (None, lst)))
    # [12, 3, 1, 99, 7, 120]
    

    Well, okay, just delete empty lines:

    lst= [12,3,1, '', 99,7,120]
    print (list (filter ('' .__ ne__, lst)))
    # [12, 3, 1, 99, 7, 120]