Python Forum

Full Version: best way to add item to list only once
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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)