Reputation: 81
I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines. my code in its ugly form:
def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
What I'm hoping for is something like:
if choice in list_x:
list_x.remove(choice)
I would like it to work for each list, would I need to loop through? any suggestions would be great! I have the workaround but I would love to learn a more elegant way of coding this!
Upvotes: 6
Views: 2993
Reputation: 6185
An alternative to the former suggestions, which is a bit clearer, is to define a helper function. So, instead of:
def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(choice)
if choice in list_d:
list_d.remove(choice)
if choice in list_e:
list_e.remove(choice)
You'd have:
def create_newlist(_list, choice):
if choice in _list:
_list.remove(choice)
lists = [list_a, list_b, list_c, list_d, list_e]
for _lst in lists:
create_newlist(_lst, choice)
Upvotes: 0
Reputation: 3159
If you use some_list.remove(item)
, only the first found match of item
is removed from the list. Therefore, it depends if the lists possibly include duplicated items, which (all) need to be removed:
list1 = ["a", "b" , "c", "d"]
list2 = ["k", "l", "m", "n"]
list3 = ["c", "b", "a", "e"]
[l.remove("a") for l in [list1, list2, list3] if "a" in l]
print(list3)
> ["c", "b", "e"]
However
In that case itertools
' filterfalse() will come in handy:
from itertools import filterfalse
def remove_val(val, lists):
return [list(filterfalse(lambda w: w == val, l)) for l in lists]
l1 = ["a", "b" , "c", "d"]
l2 = ["k", "l", "m", "n"]
l3 = ["a", "c", "b", "a", "a", "e"]
newlists = remove_val("a", [l1, l2, l3])
Then the test:
print(newlists)
> [['b', 'c', 'd'], ['k', 'l', 'm', 'n'], ['c', 'b', 'e']]
Upvotes: 3
Reputation: 3224
How about creating a list of lists and looping over that?
Something like:
lists = [list_a, list_b, list_c, list_d, list_e]
for lst in lists:
if choice in lst:
lst.remove(choice)
Upvotes: 6
Reputation: 4441
Make your list_x
a list of all your lists
Then do it this way
for each in list_x:
if choice in each:
# if is actually not required
each.remove(choice)
Upvotes: 2