Intro
This tutorial will teach you about the set data-structure in Python.
Requirements
- Know basics of Python 3 if not read here
- Knowledge of Computer Science data-structures will help
What are they?
In Python a set is a unordered collection of unique values, which are not indexed, Unlike a list/tuple. They can hold any data-type and values contained inside one set can be different. You also can’t modify an existing element when it has been added, you can however remove an element.
Creation
You can create a set similar to how you would create a list or tuple. However you just need to use certain brackets. The brackets to use are “curly braces”.
|
|
As you can see from the code above that it assigns a set with integers to the variable “amazing_numbers”. When run you should see the output below:
|
|
Adding
We can add new values to a set. We can not however add a duplicate value.
Add
First we will use the “.add()” method. This allows you to add one new value at each method call.
|
|
The code will create the output shown below:
|
|
Update
We can also add values from another set into another. This is made possible using the “.update()” method.
|
|
As you can see from the output it has added the values from the “amazing_numbers” set and placed them in the “some_random_set” set. The full output is shown below:
|
|
Accessing
Accessing sets is slightly different than a list or tuple. We can only access them through a loops.
For example we can check if a value is stored in a set. We can do this using the “in” keyword, which is shown in the code below:
|
|
From this code will will get a boolean result, if we get “True” it means that the value exists inside the set.
|
|
Removing
We can remove values from a set using several different methods.
Remove
The first method is using the “.remove()” function. This will take in the value to remove when called. It will raise an error if the value doesn’t exist.
|
|
When this is run you should see the following output:
|
|
Discard
We can also use the “.discard()” function which removes the value passed in, however unlike the “remove” function it will not raise an error if the value does not exist.
There is also a “.pop()” method, which is not covered in this tutorial
Clear
We can also clear all the values in the set. This is achieved by calling the “.clear()” function. It will not take in any arguments as it just clears all elements.
|
|
When run you will not see empty “curly braces” like you would for a list or dictionary, instead you will see the “set()” function. You can see the output of the code below:
|
|
Iteration
Like most of the collection data-structures you can also iterate over them.
|
|
When run you will see the following output:
|
|
End
There is much more to learn about sets, have a look at the official Python documentation for more in-depth knowledge.