Remove element in list with bool flag with List Comprehension

Question:

Wondering if there would be a neat way to use List Comprehension to accomplish removing an element from a list based on a bool.

example

test_list = [
     "apple",
     "orange",
     "grape",
     "lemon"
]
apple = True
    if apple:
        test_list.remove("apple")

print(test_list)

expected output

['orange', 'grape', 'lemon']

I know I could so something like:

test_list = [x for x in test_list if "apple" not in x]

But wondering if I could use a bool flag to do this instead of a string as I only want to to run if the bool is True.

Asked By: bkeesey

||

Answers:

test_list = [x for x in test_list if not (apple and x == "apple")]

Results:

>>> apple = True
>>> [x for x in test_list if not (apple and x == "apple")]
['orange', 'grape', 'lemon']

>>> apple = False
>>> [x for x in test_list if not (apple and x == "apple")]
['apple', 'orange', 'grape', 'lemon']

Note: Going by the initial example, removing one element from a list depending on a flag, I would stick to that example, which is very clear what it does:

if apple:
    test_list.remove("apple")

My list comprehension condition takes more effort to understand. Clarity beats conciseness and (premature) optimisation. There is no good reason with your example to use a list comprehension.

Also: my list comprehension is not precisely equivalent as the if - .remove(...) part, as pointed out by Edward Peters. The list comprehension will remove all elements that are "apple" (if apple is True), while the if - .remove() variant will only remove the first occurrence of "apple", and leave any remaining "apple" elements in the list.

Should you desire the first behaviour, I’d be inclined to use:

if apple:
    test_list = [item for item in test_list if item != "apple"]

which is still much clearer than the list comprehension with the double condition, while still using the practicality of a list comprehension to filter a list.

Answered By: 9769953

We can create a boolean list and use a list comprehension to get the test_list without the apple item inside:

test_list = [
     "apple",
     "orange",
     "grape",
     "lemon"
]

test_list_bool=[True if x=='apple' else False for x in test_list]

test_list=[test_list[i] for i in range(len(test_list)) if not test_list_bool[i]]

Output

>>> test_list
>>> ['orange', 'grape', 'lemon']
Answered By: Khaled DELLAL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.