Is there a more Pythonic (or succinct) way to prevent adding a duplicate to a list?
if item not in item_list:
item_list.append(item)
Or is this in fact a cheap operation?
Since @hcwsha's original solution has been replaced, I'm recording it here:
seen = set(item_list)
# [...]
if item not in seen:
seen.add(item)
item_list.append(item)
This runs in O (1) and could therefore be considered better than the one that you are currently using.
Your way is great! Set are useful for this sort of things but as previously mentioned, they don't maintain order. Other ways of writing a little more succinctly, though maybe not as clear, are show below:
item_list.append(item) if item not in item_list else None
and
item_list += [item] if item not in item_list else []
this last one can be adapted if you wanted to add multiple new_items = [item1, ...]
like so
item_list += [item for item in new_items if item not in item_list]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With