I have to append elements to a list only if the current iterated element is not already in the list.
>>> l = [1, 2]
>>> for x in (2, 3, 4):
... if x not in l:
... l.append(x)
...
>>> l
[1, 2, 3, 4]
vs
>>> l = [1, 2]
>>> [l.append(i) for i in (2, 3, 4) if i not in l]
[None, None]
>>> l
[1, 2, 3, 4]
The list comprehension gives the result is what I want, just the returned list is useless. Is this a good use case for list comprehensions?
The iteration is a good solution, but I’m wondering if there is a more idiomatic way to do this?
You could do:
This solution still works if the added list is non-unique.