Is there a way to shorten multiple nested for and if loops in python that ends with a list removing or appending an item?

Gmony5100 :

I have the following function that takes a number from a list in a list in a list (weird setup but it is necessary for the rest of the operation on my end) that sorts through all of the lists and removes a number from the innermost list. I have a few functions that append as well and I have written them in this way with a few nested for loops and if statements.

list = [['John', ['1','2','3']], ['Bob', ['4','5','6','7']], ['Jim', ['8','9']]]
def removeNumber(Number):
    for x in list:
        for y in x[1]:
            if y == Number:
                x[1].remove(Number)
removeNumber('5')
print(list)

The above block of code works, as in it removes the given number from the innermost list, but I think we can all agree it looks terrible with so many nested for loops and an if. I am pretty new to python and haven't had much practice with list comprehension.

I'm wondering if there is a way to write this using list comprehension or if there is a better way at all using another method. Better meaning fitting the mantra of "flat is better than nested". Any help on this would be much appreciated

tdelaney :

You've got a bug in that code. Removing an item in x[1] causes the outer for to skip items in the list. If you want to keep the original list, do

def removeNumber(Number):
    for x in list:
        while Number in x[1]:
            x[1].remove(Number)

But in python we typically just create new lists

def removeNumber(Number):
    for x in list:
        x[1] = [n for n in x[1] if n != Number]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21290&siteId=1