0

(Newbie question) I want to write a Python program that removes a concrete item from a set if it is present in the set.

When the set is predefined, the code goes like this:

set = {1,2,3,4,4,5,6,10}
set.discard(4)
print(set)

What would be a way to write this, so that it applies to any set of values not known beforehand? I tried the following but it didn´t work. Is there a method along those lines that does?

def set(items):
    if i in items == 4:
        set.discard(4)
    else:
        print("The number 4 is not in the set.")
print(set({1,2,4,6}))
  • Also the `set` that you posted is invalid as it has two 4s (a set cannot have duplicates). – slider Nov 16 '18 at 23:21
  • Thanks - I just realized the duplication. However, the first code works as intended when there is only one 4. I´m having difficulty with the second code. Even if I rename "set" (built-in function) to setA, it doesn´t execute. – Madrid_datalady Nov 16 '18 at 23:24
  • @slider that is a totally valid `set` literal. – juanpa.arrivillaga Nov 16 '18 at 23:26
  • @arshajii `set.discard` works just fine. – juanpa.arrivillaga Nov 16 '18 at 23:28
  • 2
    @Madrid_datalady I'm not sure I understand your question. You can just use `.discard` directly on any given set. The following: `if i in items == 4:` is incorrect, to check membership in a set (and most containers) you just use `if 4 in items`, but you don't have to check first before using `.discard`. – juanpa.arrivillaga Nov 16 '18 at 23:29
  • @juanpa.arrivillaga Thank you, this is a useful explanation. I´m just getting started with Python, so still have a lot of confusion about how to express things. – Madrid_datalady Nov 16 '18 at 23:43

1 Answers1

2

This will discard the 4 in any set passed to the function:

def discard4(items):
    if 4 in items:
        items.discard(4)
        return "Discarded"
    else:
        return "The number 4 is not in the set." 
print(discard4({1,2,6}))    # will print "The number 4 is not in the set."
print(discard4({1,2,4,6}))  # will print "Discarded"
quant
  • 2,184
  • 2
  • 19
  • 29