Python Sets

Python Sets

Python also includes a data type for the set. A python set is an unplanned collection with no duplicate elements. Basic uses of python sets are included membership testing and eliminating duplicate entries. Set objects also support mathematical operations such as union, intersection, spacing, and isometric spacing.

The curly braces or set () function can be used to create a python set. Note: To create an empty set you must use the set (), not {}; The latter creates an empty dictionary, a data structure that we discuss in the next part.

python sets


Here is a brief demonstration:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate python sets operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

Similarly, list understanding, python set understanding are also supported:

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

Python Sets Python Sets Reviewed by Sk Jha on October 14, 2019 Rating: 5

No comments:

Powered by Blogger.