Python Tutorial – Set Collection

Python Exercise Lists

Collections in Python, like the concept of collections in mathematics, are used to store unique elements, that is, the elements in a collection are unique and different from each other.

Formally, similar to a dictionary, a Python collection puts all elements in a pair of braces {}, and adjacent elements are separated by "," as follows:

{element1, element2, ..., elementn}

Among them, elementn represents the elements in the collection, and the number is not limited.

From the content point of view, the same collection can only store immutable data types, including integers, floats, strings, and tuples, and cannot store variable data types such as lists, dictionaries, and collections, otherwise the Python interpreter will Throws a TypeError. For example:

{[7,9,8]}
           

The output is:

---------------------------------------------------------------------------
TypeError        Traceback (most recent call last)
[ipython-input-124-db1220f308ba] in [module]
----> 1 {[7,9,8]}
TypeError: unhashable type: 'dict'

And it should be noted that the data must be guaranteed to be unique, because the collection will only retain one copy for each data element. Example:

{7,8,9, (1,2,3), 'a', 'a'}
           

The output is:

{(1, 2, 3), 7, 8, 9, 'a'}

Because set collections in Python are unordered, the sort order of the elements may be different each time they are output.

In fact, there are two types of collections in Python, one is a set of type, and the other is a frozenset type. The only difference is that the set type can be used to add and delete elements, while the forzenset type cannot be used to add and delete elements. This section first introduces the set type collection, and the subsequent chapters introduce the forzenset type collection.

Python - Create Set Collection

Python provides two methods for creating set collections: using {} to create and using the set function to convert lists, tuples, and other types of data into collections.

a) Create with {}

In Python, creating a collection can be done by assigning the collection directly to variables like lists, elements, and dictionaries, thereby achieving the purpose of creating collections. The syntax is as follows:

setname = {element1, element2, ..., elementn

Among them, setname represents the name of the collection. When naming it, it must conform to the Python naming convention and avoid duplicate names with Python's built-in functions.

For example:

a = {7,8,9, (1,2,3), 'a', 'a'}
print (a)
           

The output is:

{7, 8, 9, (1, 2, 3), 'a'}

b) The set function creates a collection

The set () function is a built-in function of Python. Its function is to convert iterable objects such as strings, lists, tuples, and range objects into collections. The syntax of the function is as follows:

setname = set (iteration)

Among them, iteration represents data such as strings, lists, tuples, and range objects.

Example:

set_1 = set ("www.freelearningpoints.com")
set_2 = set ([9,8,7,6,5])
set_3 = set ((1,2,3,4,5))
print ("set_1:", set_1)
print ("set_2:", set_2)
print ("set_3:", set_3)
           

The output is:

set_1: {'e', 'g', 's', 'n', 'l', 'm', '.', 'i', 't', 'p', 'f', 'r', 'o', 'c', 'a', 'w'}
set_2: {5, 6, 7, 8, 9}
set_3: {1, 2, 3, 4, 5}

Note that if you want to create an empty collection, you can only use the set function. Because a pair of {} is used directly, the Python interpreter treats it as an empty dictionary.

Python - Access Set Element

Because the elements in the collection are unordered, you cannot access elements using subscripts like lists. In Python, the most common way to access collection elements is to use a loop structure to read the data in the collection one by one.

Example:

a = {7,8,9, (1,2,3), 'a', 'a'}
for i in a:
    print (i, end = '')
           

The output is:

789(1, 2, 3)a

Since the loop structure has not yet been learned, beginners of the above code only need to understand it initially and will naturally understand after subsequent learning of the loop structure.

Python - Delete Set Collection

As with other sequence types, manual function collection types can also use del statements, for example:

a = {7,8,9, (1,2,3), 'a', 'a'}
print (a)
del (a)
print (a)
           

The output is:

{7, 8, 9, (1, 2, 3), 'a'}
---------------------------------------------------------------------------
NameError       Traceback (most recent call last)
[ipython-input-129-ce82c1db4af2] in [module]
2 print (a)
3 del (a)
----> 4 print (a)
NameError: name 'a' is not defined

The most common operations of Python set collections are adding and removing elements to the collection, and performing operations such as intersection, union, and difference between collections.

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises