Jackson Ennis
Jackson Ennis

Reputation: 335

How Do I Find Whether An Item Is Within A Set Or Not?

I have been having this annoying problem where I have an int, and I want to see if that int has an equivalence in a set. If it does, I don't want it in my "nset" values. However, when I attempt this, which seems pretty straightforward, it acts like the item has not been filtered properly.

Example Logs:

RDM is 8
RDM is not in
{1, 5, 6, 7, 8, 9}
{1, 3, 4, 5, 7, 8}
{2, 5, 6, 7, 8}

Code:

    nset = list(range(1, self.n2 + 1))

    for i in nset:
        if(i in self.valuesInRows[space[0]]):
            nset.remove(i)
        elif(i in self.valuesInCols[space[1]]):
            nset.remove(i)   
        elif(i in self.valuesInBoxes[self.spaceToBox(space[0], space[1])]):
            nset.remove(i)

    rdm = -1

    while(rdm not in nset):
        rdm = random.randint(0, self.n2)
        print("RDM {}".format(rdm))

    print("RDM is {}".format(rdm))
    print("RDM is not in")
    print(self.valuesInBoxes[self.spaceToBox(space[0], space[1])])
    print(self.valuesInRows[space[0]])
    print(self.valuesInCols[space[1]])
    print()

    return rdm

Any explanation would be fantastic, because I've looked at the documentation and it shows that this is the approach I would want to do, but I seem to be missing something.

Upvotes: 0

Views: 125

Answers (1)

thuva4
thuva4

Reputation: 1225

You are using list instead of sets. Lists are standard Python data types that store values in a sequence. Sets are another standard Python data type that also stores values. The major difference is that sets, unlike lists or tuples, cannot have multiple occurrences of the same element and store unordered values.

By definition, sets won't allow for duplicate values. In lists, Before inserting the value, you have to check the occurrence by in keyword.

  1. https://docs.python.org/3/reference/expressions.html#membership-test-operations

Upvotes: 1

Related Questions