Python – Sets

1. Format of Sets

A set is an unordered collection of unique elements.

Sets can be created using curly braces { } or the set() function. Note: To create an empty set, you must use set() instead of { }, because { } is used to create an empty dictionary.

Creation format:

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

2. Basic Operations on Sets

2.1 Adding Elements

The syntax format is as follows:

<span>s.add(x)</span>

This adds element x to the set s. If the element already exists, no action is taken.

In [1]: thisset = set(("Google", "Runoob", "Taobao"))
In [2]: thisset.add("Facebook")
In [3]: print(thisset)Out[3]: {'Facebook', 'Google', 'Runoob', 'Taobao'}

There is another method to add elements, where the parameter can be a list, tuple, dictionary, etc. The syntax format is as follows:

<span>s.update(x)</span>

x can have multiple values, separated by commas.

In [4]: thisset = set(("Google", "Runoob", "Taobao"))
In [5]: thisset.update({1,3})
In [6]: print(thisset)Out[6]: {1, 3, 'Google', 'Runoob', 'Taobao'}
In [7]: thisset.update([1,4],[5,6])
In [8]: print(thisset)Out[8]: {1, 3, 4, 5, 6, 'Google', 'Runoob', 'Taobao'}

2.2 Removing Elements

The syntax format is as follows:

<span>s.remove(x)</span>

This removes element x from the set s. If the element does not exist, an error will occur.

In [9]: thisset = set(("Google", "Runoob", "Taobao"))
In [10]: thisset.remove("Taobao")
In [11]: print(thisset)set(['Google', 'Runoob'])
In [12]: thisset.remove("Facebook")    # Error occurs if it does not exist---------------------------------------------------------------------------KeyError                                  Traceback (most recent call last)&lt;ipython-input-12-53a786b3179c&gt; in &lt;module&gt;()----&gt; 1 thisset.remove("Facebook")
KeyError: 'Facebook'

Additionally, there is another method to remove elements from the set, which does not raise an error if the element does not exist. The format is as follows:

<span>s.discard(x)</span>

In [13]: thisset = set(("Google", "Runoob", "Taobao"))
In [14]: thisset.discard("Facebook")    # No error occurs if it does not exist
In [15]: print(thisset)    set(['Google', 'Taobao', 'Runoob'])

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

<span>s.pop()</span>

In [16]: thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
In [17]: thisset.pop()Out[17]: 'Facebook'
In [18]: print(thisset)set(['Google', 'Taobao', 'Runoob'])

2.3 Counting Elements in a Set

The syntax format is as follows:

<span>len(s)</span>

This counts the number of elements in the set s.

In [19]: thisset = set(("Google", "Runoob", "Taobao"))
In [20]: len(thisset)Out[20]: 3

2.4 Clearing a Set

The syntax format is as follows:

<span>s.clear()</span>

This clears the set s.

In [21]: thisset = set(("Google", "Runoob", "Taobao"))
In [22]: thisset.clear()
In [23]: print(thisset)set([])

2.5 Checking for Element Existence

The syntax format is as follows:

<span>x in s</span>

This checks if element x exists in the set s. Returns True if it exists, False if it does not.

In [24]: thisset = set(("Google", "Runoob", "Taobao"))
In [25]: "Runoob" in thissetOut[25]: True
In [26]: "Facebook" in thissetOut[26]: False

3. Set Operations

In [27]: s_a ={1,2,3,4,5,6}
In [28]: s_b = {4,5,6,7,8,9}
# Union, two ways to write, results are the sameIn [29]: print(s_a | s_b)set([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [30]: print(s_a.union(s_b))  set([1, 2, 3, 4, 5, 6, 7, 8, 9])
# IntersectionIn [31]: print(s_a &amp; s_b)set([4, 5, 6])
In [32]: print(s_a.intersection(s_b))set([4, 5, 6])
# Difference A - (A&amp;B)In [33]: print(s_a - s_b)set([1, 2, 3])
In [34]: print(s_a.difference(s_b))set([1, 2, 3])

# Symmetric Difference (A|B) - (A&amp;B)In [35]: print(s_a ^ s_b)set([1, 2, 3, 7, 8, 9])
In [36]: print(s_a.symmetric_difference(s_b))set([1, 2, 3, 7, 8, 9])

Leave a Comment