Ch Y Duan
Ch Y Duan

Reputation: 155

Python remove sublist in a list if specific element inside this sublist

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]]

Upvotes: 4

Views: 1074

Answers (7)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

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

Upvotes: 4

Pedro Lobito
Pedro Lobito

Reputation: 98861

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

Upvotes: 1

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

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]]

Upvotes: 1

Robert
Robert

Reputation: 36733

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]]

Upvotes: 1

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27191

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!

Upvotes: 1

MSeifert
MSeifert

Reputation: 152577

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]]

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122326

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.

Upvotes: 1

Related Questions