Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condensing multiple if statements in python

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!

like image 519
Brian F Avatar asked Sep 10 '16 15:09

Brian F


People also ask

How do you handle multiple if conditions in Python?

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.

How do you write 3 if statements in Python?

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!")

How do you write an if statement with multiple conditions?

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)


1 Answers

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)
like image 95
gowrath Avatar answered Oct 05 '22 23:10

gowrath