Python Sets

Python sets is a collection which is unordered and we can’t access element using index.

It uses curly brackets –

>>> S = {“welcome”, “to”, “the”, “codersarts”}

Accessing sets items

We can access sets items using for loop easily.

>>> S = {“welcome”, “to”, “the”, “codersarts”}

      for x in S:         

               print(x)

Adding item to the sets:

We can add the item to the list using add() function.

>>> S.add(“hi”)

Adding more than one item then use update()

>>> S.update(“hi”, "hello")

Finding length of sets

Length of sets can be found using the len().

>>> len(S)

Removing item of sets

Sets item removed using the remove()

It removes the value of sets.

>>> S.remove(“hi”)

Remove show error if the item not exit, to solve this better use is discarded() method, which can’t show an error if data not exits.

We will also remove the item using pop(), it removes the last item but sets are unordered so we can’t identify which item is removed from sets.

del delete sets completely.

Join sets

It uses union() method to join the sets

>>> set3 = set1.union(set2)