Python Forum
best way to add item to list only once - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: best way to add item to list only once (/thread-26412.html)



best way to add item to list only once - Phaze90 - Apr-30-2020

Hi,

what is the more effective way of the both below?
Or is there a third variant?

def add_only_once_to_list(in_obj, in_list,):
    if in_obj not in in_list:
        in_list.append(in_obj)
Or with a local set:

def add_only_once_to_list(in_obj, in_list,):
    temp_set = set(in_list)
    temp_set.add(in_obj)
    in_list = list(temp_set)



RE: best way to add item to list only once - bowlofred - May-01-2020

If it were just a one-time thing for one object, I'd do the first one.

If it was happening more than once, I'd wonder why you're retaining the list if uniqueness is important.

If you needed to add several objects to the list uniquely, I'd do similar to #2, but use a set comprehension.

def add_objects_if_not_in_list(objs_to_add, in_list):
    return list({x for x in itertools.chain(in_list, objs_to_add)})
The disadvantage of this and #2 from above is that the set would destroy any order of the original list. (which may be the only reason you would prefer to keep the list than the set)