Remove multiple items from a Python list in just one statement

前端 未结 7 1547
逝去的感伤
逝去的感伤 2020-12-02 06:28

In python, I know how to remove items from a list.

item_list = [\'item\', 5, \'foo\', 3.14, True]
item_list.remove(\'item\')
item_list.remove(5)
7条回答
  •  醉话见心
    2020-12-02 06:59

    You can do it in one line by converting your lists to sets and using set.difference:

    item_list = ['item', 5, 'foo', 3.14, True]
    list_to_remove = ['item', 5, 'foo']
    
    final_list = list(set(item_list) - set(list_to_remove))
    

    Would give you the following output:

    final_list = [3.14, True]
    

    Note: this will remove duplicates in your input list and the elements in the output can be in any order (because sets don't preserve order). It also requires all elements in both of your lists to be hashable.

提交回复
热议问题