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!
Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.
Example. #!/usr/bin/python3 var1 = 100 if var1: print ("1 - Got a true expression value") print (var1) var2 = 0 if var2: print ("2 - Got a true expression value") print (var2) print ("Good bye!")
When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With