Python3 Sets

A set is an unordered sequence of unique elements.

Elements in a set do not repeat, and common set operations such as intersection, union, and difference can be performed.

Curly braces can be used{ }to create a set, with elements separated by commas,, or you can also use theset()function to create a set.

Creation format:

parame = {value01,value02,...}
或者
set(value)

The following is a simple example:

set1 = {1, 2, 3, 4}            # 直接使用大括号创建集合
set2 = set([4, 5, 6, 7])      # 使用 set() 函数从列表创建集合

Note:To create an empty set you must use set()rather than{ }, because{ }is used to create an empty dictionary.

More example demonstrations:

Example (Python 3.0+)

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # Here demonstrates the deduplication function
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # Quickly check whether an element is in a set
True
>>> 'crabgrass' in basket
False

>>> # The following shows operations between two sets.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # Elements contained in set a but not in set b
{'r', 'd', 'b'}
>>> a | b                              # All elements contained in set a or set b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # Elements contained in both set a and set b
{'a', 'c'}
>>> a ^ b                              # Elements not contained in both a and b at the same time
{'r', 'd', 'b', 'm', 'z', 'l'}

Similar to list comprehensions, sets also support set comprehensions:

Example (Python 3.0+)

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

Basic Set Operations

1. Adding Elements

The syntax format is as follows:

s.add( x )

Add element x to set s; if the element already exists, no operation is performed.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Example'}

There is also another method that can add elements, and its parameter can be a list, tuple, dictionary, etc. The syntax format is as follows:

s.update( x )

There can be multiple x values, separated by commas.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Example'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Example'}
>>>

2. Removing Elements

The syntax format is as follows:

s.remove( x )

Remove element x from set s; if the element does not exist, an error will occur.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Example'}
>>> thisset.remove("Facebook")   # An error occurs if it does not exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
>>>

In addition, there is another method that also removes elements from a set, and no error occurs if the element does not exist. The format is as follows:

s.discard( x )

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> thisset.discard("Facebook")  # No error occurs if it does not exist
>>> print(thisset)
{'Taobao', 'Google', 'Example'}

We can also randomly delete an element from a set. The syntax format is as follows:

s.pop() 

Script Mode Example (Python 3.0+)

thisset = set(("Google", "Example", "Taobao", "Facebook"))
x = thisset.pop()

print(x)

Output result:

Example

The test results are different each time it is executed multiple times.

The pop method of a set arranges the set in an unordered order, and then deletes the leftmost first element of this unordered set.

3. Counting the Number of Elements in a Set

The syntax format is as follows:

len(s)

Count the number of elements in set s.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> len(thisset)
3

4. Clearing a Set

The syntax format is as follows:

s.clear()

Clear set s.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()

5. Checking Whether an Element Exists in a Set

The syntax format is as follows:

x in s

Determine whether element x is in set s; return True if it exists, and False if it does not.

Example (Python 3.0+)

>>> thisset = set(("Google", "Example", "Taobao"))
>>> "Example" in thisset
True
>>> "Facebook" in thisset
False
>>>

Complete List of Built-in Set Methods

Method Description
add()Add elements to a set
clear()Remove all elements from a set
copy()Copy a set
difference()Return the difference of multiple sets
difference_update()Remove an element from a set if it also exists in the specified set.
discard()Delete the specified element from a set
intersection()Return the intersection of sets
intersection_update()Return the intersection of sets.
isdisjoint()Determine whether two sets contain the same elements; return True if they do not, otherwise return False.
issubset()Determine whether the specified set is a subset of the parameter set of this method.
issuperset()Determine whether the parameter set of this method is a subset of the specified set.
pop()Randomly remove an element
remove()Remove the specified element
symmetric_difference()Return a set of elements that are not repeated in the two sets.
symmetric_difference_update()Remove from the current set the elements that are the same as those in another specified set, and insert the different elements from the other specified set into the current set.
union()Return the union of two sets
update()Add elements to a set
len()Count the number of elements in a set
Other Extensions