0

The syntax for checking if an item is already in a list and then adding it to a list if it is not is:

foo = []
if item not in foo:
    foo.append(item)
    # do something

This can execute code on the condition that the item is not in foo. This syntax seems to duplicate the logic of a set datatype in python, yet the following syntax does not exist;

bar = set()
if not bar.add(item):
    # do something

but add() returns nothing, so this is not possible. So how does one execute some logic conditionally on an item being in a set?

Note: the reason a set is desired is the operation of adding a unique value to a set is of O(1), whereas the same operation is O(n) on a list.

leafystar
  • 129
  • 1
  • 1
  • 7

1 Answers1

1

Just remove the if.

bar = set()
bar.add(item):
# do something

Note that you have foo.append(item) when using a list. The only thing that changes is the function name when you use a set.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • I want to execute code on the condition that the item is not in the set, not just add it, I therefore need an if statement. – leafystar Aug 27 '19 at 15:33
  • 1
    @leafystar You do not need an `if` statement in this case because adding an item that's already in a set to the set would result in nothing happening, just like the behavior of an `if item not in bar:` statement, so adding an `if` statement would be redundant. – blhsing Aug 27 '19 at 15:35
  • @leafystar To check if an element is in a set is exactly the same as checking if an element is in a list: `if item in bar:`. On the other hand, adding an element to a set and adding an element to a list are similar; the only difference is the name of the method you want to use. – Code-Apprentice Aug 27 '19 at 16:18
  • @leafystar To add to blhsing and my previous comments, I suggest that you write out what you want to do in words and then translate those words into code. For example, "if item is in set named bar do something" translates to `if item in bar:`. On the other hand, "add item to set named bar" translates to `bar.add(item)`. Note how the words are describing two very different actions and so the code is different for each one. – Code-Apprentice Aug 27 '19 at 17:04