Learn Before
  • Set

Concept

Set Operations

Different operations can be performed on a set. Important operations include:

  • Accessing a set item:

You can access all items in the set by looping over it, as shown.

for x in set: print(x)

You can check if a specific value is present in the set as well.

print(x in set)
  • Adding a set item:

You can add a set item by using the add() method as shown.

set.add(x)

You may also want to add all items from a different iterable (does not need to be a set) to your set. In this case, you may use the update method.

setA = {"apple", "orange", "banana"} setB = {"kiwi", "mango", "pineapple"} setB.update(setA)
  • Removing a set item:

You can remove a set item by using the remove() method as shown.

set.remove(x)
  • Joining two sets:

You can create a set that contains all the items from two sets by using the union operation. This is similar to adding all items from a different iterable, but different because rather than adding all elements from setA to setB, you are creating a new set (setC) that contains all elements of setA and setB.

setA = {"apple", "orange", "banana"} setB = {"kiwi", "mango", "pineapple"} setC = setB.union(setA)

Other methods that may be used include:

  • clear()
  • copy()
  • difference()
  • discard()
  • intersection()
  • isdisjoint()
  • issubset()
  • issuperset()
  • pop()
  • symmetric_difference()

0

1

Updated 2021-06-01

Tags

Python Programming Language

Data Science

Related
Learn After