Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more Pythonic way to prevent adding a duplicate to a list?

Tags:

python

list

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?

like image 661
lofidevops Avatar asked Nov 30 '22 00:11

lofidevops


2 Answers

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.

like image 85
Johnsyweb Avatar answered Dec 10 '22 16:12

Johnsyweb


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]
like image 44
cdhagmann Avatar answered Dec 10 '22 16:12

cdhagmann