11. Python Set

Sets is a collections of unordered items. Python set is similar with these mathematical definitions..

  • The elements will not be duplicated.
  • It is immutable for specific elements but the whole is mutable.
  • Not support for indexing and slicing.

Set is defined by placing the elements inside curly braces. Example from definitions above.

>>> numbers = {1, 1, 2, 2, 2, 4, 4, 5, 5, 5}
>>> numbers # set elements will not be duplicated
{1, 2, 4, 5}
>>> days = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'}
>>> days # days is printed with unordered way
{'Wed', 'Sun', 'Tue', 'Thu', 'Mon', 'Sat', 'Fri'} 
>>> days[0] # not support for indexing
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    days[0]
TypeError: 'set' object does not support indexing
>>> days[1:3] # not support for slicing 
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    days[1:3]
TypeError: 'set' object is not subscriptable
>>> days[0] = 'Mon'
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    days[0] = 'Mon'
TypeError: 'set' object does not support item assignment
>>> days = {'Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday', 'Sun'} # but the whole is mutable
>>> days
{'Saturday', 'Sun', 'Monday', 'Friday', 'Tuesday', 'Wednesday'}

Notice that set is printed in unordered way, not support for indexing as well as slicing, immutable, and it is mutable for the whole. It is also possible to use the set() constructor to create a set and convert other data structures type such as strings, list, and tuple to set. Example

fruits = set(('Banana','Apple', 'Pear')) # use double brackets
print(fruits)
# - convert list to set
fruits = ['Banana', 'Apple', 'Pear']
print(set(fruits))
# - convert tuple to set
fruits = ('Banana', 'Apple', 'Pear')
print(set(fruits))
# - convert string to set
strings = 'aasdfffa'
print(set(strings))

11.2 Accessing Values in Sets

Python sets didn't support for indexing and slicing, but iterate over the sets elements instead. Example

days = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'}
for day in days:
    print(day)

11.3 Update the Set

As we have mentioned above that set is immutable, here we only can add an item using add() method and delete an item using remove() method or discard() method. Example

fruits = set(('Banana','Apple', 'Pear')) 
fruits.add('Cherry')
print(fruits)
fruits.remove('Apple')
print(fruits)
fruits.discard('Banana')
print(fruits)

11.2 Set Operations

Some basic set operations:

  • Union operation will produce a new set that contain all distinct element from two sets.
  • Intersection operation will produce a new set that contain only the common elements from two sets.
  • Difference operation will produce a new set that contain only from the first set and nothing from the second set.
  • Compare operation to check whether the set is subset or superset of another set.

Example

a = {1, 2, 3}
b = {1, 2, 3, 4, 5}

# - Union of sets
c = a | b
print(c)  # {1, 2, 3, 4, 5}

# - Intersection of sets
c = a & b
print(c)  # {1, 2, 3}

# - Difference of sets
c = b - a
print(c)  # {4, 5}

# - Compare sets, subset ( <= ) and superset( >= )
c = a <= b
print(c)  # True
c = a >= b
print(c)  # False

Subscribe to receive free email updates:

Related Posts :

  • 3. Python Variables and Data Types 3.1 Variables Variables are reserved memory locations to store values. Python interpreter will allocates and decides what can be stored i… Read More...
  • 5. Python User Input In the previous tutorials, we directly assign the values into variables before we run the program. How about if you want to enter your own… Read More...
  • 7. Python Loops In Programming, there might be situation that you need to execute particular block of code multiple times. Python loop provides various s… Read More...
  • 2. First Program Now that you have Python ready, we can continue to write our first program. Type the following code in any text editor or IDE then save … Read More...
  • 1. Python Introduction Python is a cross-platform programming langauge that run on mulitple OS like Windows, Mac OS X, Linux and Unix. Today's most Linux and Mac… Read More...

0 Response to "11. Python Set"

Post a Comment