Python Forum
best way to add item to list only once
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
best way to add item to list only once
#1
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)
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  count item in list korenron 7 283 Jul-01-2021, 01:46 PM
Last Post: deanhystad
  Time.sleep: stop appending item to the list if time is early quest 0 357 Apr-13-2021, 11:44 AM
Last Post: quest
  How to run a pytest test for each item in a list arielma 0 488 Jan-06-2021, 10:40 PM
Last Post: arielma
  How do I add a number to every item in a list? john316 2 433 Oct-28-2020, 05:29 PM
Last Post: deanhystad
  Ignoring a list item hank4eva 2 714 Aug-17-2020, 08:40 AM
Last Post: perfringo
  Select correct item from list for subprocess command pythonnewbie138 6 905 Jul-24-2020, 09:09 PM
Last Post: pythonnewbie138
  Why is the item not in list when it is DanielCook 2 655 Jul-08-2020, 07:38 PM
Last Post: deanhystad
  item from a line to list however when i print the line instead of words i get letters Sutsro 5 898 Apr-22-2020, 02:39 PM
Last Post: deanhystad
  Help removing asterisk item in a nested list. bmcguire 3 796 Apr-06-2020, 02:35 PM
Last Post: snippsat
  If item in list = true, Output = xx kroh 0 601 Feb-19-2020, 09:17 AM
Last Post: kroh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020