4

For example

list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

I want the sublist including any value inside the list of specific element be removed from the list.
So the element [2,1],[2,3],[13,12],[13,14] should be removed from the list.
the final output list should be[[1,0],[15,13]]

1
  • 5
    Why would [15, 13] remain? It does contain a 13. Commented May 27, 2017 at 21:44

7 Answers 7

4
listy=[elem for elem in listy if (elem[0] not in list_of_specific_element) and (elem[1] not in list_of_specific_element)]

Using list comprehension one-liner

Sign up to request clarification or add additional context in comments.

4 Comments

but don't use list as a var name as it is the name of a built in function
It is the variable name that the question-asker used
@whackamadoodle3000 That doesn't mean you've to repeat the same mistake
Changed it to listy
2

You could use set intersections:

>>> exclude = {2, 13}
>>> lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
>>> [sublist for sublist in lst if not exclude.intersection(sublist)]
[[1, 0]]

Comments

1

You could write:

list_of_specific_element = [2,13]
set_of_specific_element = set(list_of_specific_element)
mylist = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
output = [
    item
    for item in mylist
    if not set_of_specific_element.intersection(set(item))
]

which gives:

>>> output
[[1, 0]]

This uses sets, set intersection and list comprehension.

Comments

1

A simple list-only solution:

list = [x for x in list if all(e not in list_of_specific_element for e in x)]

And you really shouldn't call it list!

Comments

1

Filter & lambda version

list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

filtered = filter(lambda item: item[0] not in list_of_specific_element, list)

print(filtered)

>>> [[1, 0], [15, 13]]

Comments

1

You can use list comprehension and any() to do the trick like this example:

list_of_specific_element = [2,13]
# PS: Avoid calling your list a 'list' variable
# You can call it somthing else.
my_list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
final = [k for k in my_list if not any(j in list_of_specific_element for j in k)]
print(final)

Output:

[[1, 0]]

Comments

1

I guess you can use:

match = [2,13]
lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

[[lst.remove(subl) for m in match if m in subl]for subl in lst[:]]

demo

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.