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
.
Advertisement
Answer
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.