Python Tutorials - Herong's Tutorial Examples - v2.15, by Herong Yang
Data Type - 'set' for Unordered Collection
This section describes the 'set' data type, which stores a collection of unordered and unique elements. 'set' data objects are mutable.
What Is the "set" Data Type? "set" is the mutable collection data type in Python. Each element in a "set" object is a unique hashable object. A "set" object can be viewed as a "dict" object with "None" values for all keys.
"set" data type has the following main Features.
1. "set" data objects can be created in several ways:
2. Elements in a "set" object are unordered and can not be accessed by positions.
>>> x = {'apple', 'orange'} >>> type(x) <class 'dict'> >>> x = {"point", (1,1)} >>> x {'point', (1, 1)} >>> x = {"point", [1,1]} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
3. Elements in a "set" object must be unique. So they must be immutable and hashable.
>>> x = {'apple', 'orange', 'app'+'le'} >>> x {'orange', 'apple'} >>> x = {'apple', 'orange', 'app'+'le'} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'set' object is not subscriptable
4. "set" objects support the following operations:
Syntax Operation Note ---------- ------------- ----------------------- x | y Union Creates a new "set" x & y Intersection Creates a new "set" x - y Difference Creates a new "set" x ^ y Symmetric difference Creates a new "set" k in x Look up k is an object k not in x Look up Same as !(k in x) x <= y Is subset x < y Is proper subset x >= y Is superset x > y Is proper superset
5. Some built-in functions are provided for "dict" objects.
6. Some instance/class methods are provided for "set" objects.
If you want an immutable collection, you can use the "frozenset" cast function to create a "frozenset" object.
Table of Contents
Common Features of All Data Types
Data Type - NoneType for Nothing
Data Type - 'bool' for Boolean Values
Data Type - 'int' for Integer Values
Data Type - 'float' for Real Numbers
Data Type - 'bytes' for Byte Sequence
Data Type - 'str' for Character String
Data Type - 'tuple' for Immutable List
Data Type - 'list' for Mutable List
►Data Type - 'set' for Unordered Collection
Data Type - 'dict' for Dictionary Table
Variables, Operations and Expressions
Function Statement and Function Call
List, Set and Dictionary Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager