Skip to content
Advertisement

Remove element in list with bool flag with List Comprehension

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

JavaScript

expected output

JavaScript

I know I could so something like:

JavaScript

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

JavaScript

Results:

JavaScript

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:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement