Difference between revisions of "Set"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(add content)
m (Intersection and union: reword)
Line 47: Line 47:
  
 
== Intersection and union ==
 
== Intersection and union ==
Any element which is in both <code>s1</code> and <code>s2</code> will appear in their {{plain link|//en.wikipedia.org/wiki/Intersection_(set_theory)|intersection}}. In Python, the intersection of <code>s1</code> and <code>s2</code> is given by <code>s1 & s2</code> or <code>s1.intersection(s2)</code>. Example:
+
Any element that is in both sets will appear in their {{plain link|//en.wikipedia.org/wiki/Intersection_(set_theory)|intersection}}. In Python, the intersection of <code>s1</code> and <code>s2</code> is given by <code>s1 & s2</code> or <code>s1.intersection(s2)</code>. Example:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
>>> s1 = {1, 2, 3}
 
>>> s1 = {1, 2, 3}

Revision as of 09:17, 4 June 2014

In Python, a set is an unordered collection of unique, immutable objects. It supports adjunction, membership testing, union, and intersection, among other set operations.

Creation

A set is created by enclosing comma-separated values in braces:

>>> {1, 2, 2, 3}
{1, 2, 3}

Alternatively, a set can also be constructed by set(s) for any sequence s. An empty set is constructed by set() (not {}). Example:

>>> set(['one', 'one', 'two'])
{'one', 'two'}

Length

The number of elements in set s is given by len(s).

Adjunction

Adjunction means to add an element to a set if it is not already present. An object o is adjoined to set s by s.add(o). Example:

>>> s = set() # create empty set
>>> s.add(1)
>>> s.add(2)
>>> s.add(2)
>>> s.add(3)
>>> s
{1, 2, 3}

Removal

To remove an object o from set s, use s.remove(o). Example:

>>> s = {1, 2, 3}
>>> s.remove(2)
>>> s
{1, 3}

Membership test

To test if object o is an element of set s, use o in s. Example:

>>> s = {1, 2, 3}
>>> 3 in s
True

Intersection and union

Any element that is in both sets will appear in their intersection. In Python, the intersection of s1 and s2 is given by s1 & s2 or s1.intersection(s2). Example:

>>> s1 = {1, 2, 3}
>>> s2 = {1, 3, 5}
>>> s1 & s2
{1, 3}
>>> s1.intersection(s2)
{1, 3}

The union is the merger of two sets. Any element in s1 or s2 will appear in their union. In Python, the union of s1 and s2 is given by s1 | s2 or s1.union(s2). Example:

>>> s1 = {0, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1 | s2
{0, 1, 2, 3, 4, 5}
>>> s1.union(s2)
{0, 1, 2, 3, 4, 5}

Iteration

A set is an iterable, so its elements can be iterated through in a for loop:

>>> s = {1, 2, 3}
>>> for elem in s:
...     print(elem)
...
1
2
3
However, since sets are unordered, it is undefined which order the iteration will follow.

Sources