No, it's not a Pythonic use of a ternary.
Let's put the question aside for a second and look at:
a = [1, 2, 3]
print(a.remove(2))
Well, that gives us None
because .remove()
works in place.
Now, thinking about a ternary; why might we want that? Usually it would be due to some decision over an assignment:
a = [1, 2, 3]
b = "foo" if a[0] == 1 else "bar"
print(b)
If we apply this kind of model to your ternary, you will always get None
. It's somewhat similar to using list comprehensions for side effects.
a = [1, 2, 3]
print(a.remove(2) if 2 in a else None)
print(a.remove(10) if 10 in a else None)
If the operation is always going to return None
anyway, then any reader of the code is going to ask why you even bothered with the ternary. There must be some underlying reason, right, because you have an else
case even when it's effectively a no-op because the value wasn't found. But I, as a reader, can't determine whether the condition was True
or False
because I'm going to get None
either way.
As stated in the comments, you can do this in one line:
a = [1, 2, 3]
if 2 in a: a.remove(2)
print(a)
Your intent here is more clear because there is no need for a fall-back ternary condition. Even so, chasing lines like this is pointless, but it's better than the ternary.
Not only that but, as @nineteendo points out, you'll have issues with linters by compressing the if
check to a single line: see CO321 and, more generally, PEP8