Delete item from all lists simultaneously

Suppose I have 3 lists,

list_of_fruits = ["apple", "banana", "orange"]

list_of_orange_things = ["carrot", "orange", "basketball"]

list_of_colors = ["orange", "green", "blue"]

Is there a way to delete "orange" from all lists simultaneously, without specifically addressing any individual list?

This program may have dozens of lists when it's done. At a certain point while running the program, it will be important for me to remove "orange" from ALL lists, so I want to make sure that I don't miss any by mistake.


This is an issue because my program will be generating and deleting many items and putting them into certain lists, all under different circumstances. I don't want to address every single list at every instance that an item should be deleted if there is an alternative that allows me to remove an item from ALL lists in fewer lines (to reduce clutter, and error).

2 answers

  • answered 2017-06-17 19:37 Ajax1234

    You can try this:

    s = "orange"
    
    list_of_fruits = ["apple", "banana", "orange"]
    
    list_of_orange_things = ["carrot", "orange", "basketball"]
    
    list_of_colors = ["orange", "green", "blue"]
    
    new_list = [list_of_fruits, list_of_orange_things,list_of_colors]
    
    final_list = [[b for b in i if b != s] for i in new_list]
    

    Output:

    [['apple', 'banana'], ['carrot', 'basketball'], ['green', 'blue']]
    

    This basic algorithm iterates over the lists contained in new_list and filters out any occurrence of the string s. But as @Willem Van Onsem pointed out, you will want to find a new way of storing your lists so you can iterate through everyone once, such as a list within a list.

  • answered 2017-06-17 19:37 John Dengis

    Simply keep a list of all your lists, add a new list to that list when it is created, and when you need to delete something from all the lists, iterate through your list of lists.