'remove sublist if it contains a specific value

How can i remove the full sublist if it contains a specific value?

A=[["A","no","yes","small"],
 ["B","yes","no","medium"],
 ["C","yes","yes","large"],
 ["D","yes","yes","small"],
 ["E","yes","no","medium"],
 ["F","yes","yes","small"]]

#find the index of each sublist with the value "small"
small=[]
for x in A:
    if "small" in x:
        small.append(A.index(x))
       
print(small)

#Output:
#[0, 3, 5]


#Desired output:
[["B","yes","no","medium"],
["C","yes","yes","large"],
["E","yes","no","medium"]]


How can remove all sublists with the value small?



Solution 1:[1]

List comprehensions

Given that you need to both iterate and remove items from a list, your best bet is to use Python's list comprehensions.

List comprehensions offer you a way to filter through an already existing list given some conditions. In your case, you only want the items (lists, in this example) from you list A that do not contain the string "small". One simple solution for your problem then, would be the next.

A = [["A", "no", "yes", "small"],
     ["B", "yes", "no", "medium"],
     ["C", "yes", "yes", "large"],
     ["D", "yes", "yes", "small"],
     ["E", "yes", "no", "medium"],
     ["F", "yes", "yes", "small"]]

solution = [sublist for sublist in A if "small" not in sublist]
print(solution)

The list comprehension above can be read as: create a new list with elements that are in A only if they do not contain the "small" string.

Iterating and removing

It is true that in your question you ask how to remove items from a list if they fulfill a certain condition. This however could lead to bugs depending on how it is implemented given that while iterating, when you do remove an element, all elements in the list will be shifted 'to the left' one position, making you skip some of them on the way. For example, one could think that a possible solution would be something like:

for index, sublist in enumerate(A):
    if "small" in sublist:
        A.pop(index)

In your example, this gives the correct answer, but it is still a bug. We can check, for example, that if the second sublist contains the string "small", then it will skip it.

Solution 2:[2]

small = [x for x in A if 'small' not in x]
print(small)

Output:

[['B', 'yes', 'no', 'medium'], 
['C', 'yes', 'yes', 'large'], 
['E', 'yes', 'no', 'medium']]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 BeRT2me