Sets

A set is defined as a collection of elements that can be of different types. The elements are enclosed within { }. For example, have a look at the following code block:

>>> green = {'grass', 'leaves'}
>>> print(green)
{'grass', 'leaves'}

The defining characteristic of a set is that it only stores the distinct value of each element. If we try to add another redundant element, it will ignore that, as illustrated in the following:

>>> green = {'grass', 'leaves','leaves'}
>>> print(green)
{'grass', 'leaves'}

To demonstrate what sort of operations can be done on sets, let's define two sets:

  • A set named yellow, which has things that are yellow
  • Another set named red, which has things that are red

Note that some things are common between these two sets. The two sets and their relationship can be represented with the help of the following Venn diagram:

If we want to implement these two sets in Python, the code will look like this:

>>> yellow = {'dandelions', 'fire hydrant', 'leaves'}
>>> red =
{'fire hydrant', 'blood', 'rose', 'leaves'}

Now, let's consider the following code, which demonstrates set operations using Python:

>>> yellow|red
{'dandelions', 'fire hydrant', 'blood', 'rose', 'leaves'}
>>> yellow&red
{'fire hydrant'}

As shown in the preceding code snippet, sets in Python can have operations such as unions and intersections. As we know, a union operation combines all of the elements of both sets, and the intersection operation will give a set of common elements between the two sets. Note the following:

  • yellow|red is used to get the union of the preceding two defined sets.
  • yellow&red is used to get the overlap between yellow and red. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.161.77