Remove an element from nested lists with mixed structures (lists and integers) in Python

Viewed 294

Consider the lists:

assigned = [4,8]
matching = [['B', [4, 5, 6]], ['C', [7, 8, 9]]]

I am trying to remove given integers with the following code

for ii in range(len(assigned)):
    while any(assigned[ii] in x for x in matching):
        matching.remove(assigned[ii])

I have two problems here. First one is to get into the inner lists. Right now the code does nothing because there is no matching.

Second problem, I tried this:

t = ['B', [4, 5, 6]]
if any(4 in x for x in l2):

And the result was an error:

if any(4 in x for x in l2):
TypeError: 'in <string>' requires string as left operand, not int

Is there any way to achieve both in no more than two lines of code: found matching in nested lists and remove those matchings?

2 Answers

Here's one way using a nested list comprehension:

matching = [[i[0], [j for j in i[1] if j not in assigned]] for i in matching]
print(matching)

Output:

[['B', [5, 6]], ['C', [7, 9]]]

Here is another approach with list comprehension if you prefer to use .remove()

assigned = [4,8]
matching = [['B', [4, 5, 6]], ['C', [7, 8, 9]]]
[item[1].remove(x) for item in matching for x in item[1] if x in assigned]
print(matching)
# [['B', [5, 6]], ['C', [7, 9]]]

Above is basically a list comprehension version of:

for item in matching:
    for x in item[1]:
        if x in assigned:
            item[1].remove(x)
Related