ScanSkill

set in Python

The set in Python is used to store values like an array and ensure there are no duplicates. i.e. set is a list of unique items.

Syntax

  • Empty set initialization
set_name = set()
  • Non-empty set initialization
set_name = set([value1, value2])
  • Add to a set
set_name.add(value3)

Note:

  • Sets can be combined, using union (| symbol), intersection (& symbol), difference (- symbol), and symmetric difference (^ symbol).
  • The keywords 'in' and 'not in' can be used to check for the existence of values in a set.

Example

>>> integers = set([1, 2, 3, 4, 5])
>>> integers.add(6)
>>> integers
{1, 2, 3, 4, 5, 6}