1

I have a function that takes a list of lists, as well as a regular list as arguments. Basically, all of these list items here start with a unique number. I want the first element of the second list to test against the first element of each individual list in the first list, and if they match, remove that list from listo1. I made a short example that doesn't work at all:

def deleteList(listo1, listo2):
    if (listo2 in listo1):
        listo1.remove(listo2)
        print(listo1)

def main():
    deleteList([[1000, 1],[2000, 2],[3000, 3]], [1000, 77])

So I'm trying to make listo2 search listo1 for anything that begins with the 1000 element. In this case, it should remove the first list [1000, 1] from listo1. How can I do this?

2 Answers 2

2

If you only care about the first element in listo2, you can make something like:

def deleteList(listo1, listo2):
    for insidelist in listo1:
        if listo2[0] == insidelist[0]:
             listo1.remove(insidelist)
    print(listo1)

def main():
    deleteList([[1000, 1],[2000, 2],[3000, 3]], [1000, 77])
Sign up to request clarification or add additional context in comments.

Comments

2

You can use list comprehension as a filter, like this

def deleteList(listo1, listo2):
    return [item for item in listo1 if item[0] != listo2[0]]

print deleteList([[1000, 1],[2000, 2],[3000, 3]], [1000, 77])
# [[2000, 2], [3000, 3]]

If you want to do it as an in-place operation, you can do this

def deleteList(listo1, listo2):
    listo1[:] = [item for item in listo1 if item[0] != listo2[0]]

l1 = [[1000, 1],[2000, 2],[3000, 3]]
deleteList(l1, [1000, 77])
print l1
# [[2000, 2], [3000, 3]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.