This section deals with sets. Sets are also an area of data structure. However, this section is explained as a supplementary matter, so you can omit the set.
However, for those who are thinking of taking the Fundamental Information Technology Engineer Examination, the questions will be given in set theory and set calculation. You should also take a look at those who choose Python for afternoon problems.
Please note that ** "set" ** may be ** "set" ** depending on the book.
Now let's create a set. Enter the following code in the ** Python console **.
>>> S = {1, 2, 3, 4}
>>> S
{1, 2, 3, 4}
The set is expressed by enclosing it in ** {} **. In the dictionary, the keys and values are described in ** {} ** separated by ** ":" ** (colon), but when the colon disappears, it becomes a set.
Now let's add an element to the set. For sets, use the ** add ** method instead of append. Enter the following code in the ** Python console **. Display the contents of the variable ** S ** once and then execute.
>>> S
{1, 2, 3, 4}
>>> S.add(5)
>>> S
{1, 2, 3, 4, 5}
You should have confirmed that the element was added at the end of the set.
Now, in this state, execute ** add (5) ** again to output.
>>> S.add(5)
>>> S
{1, 2, 3, 4, 5}
As you can see from the results, sets allow you to create unique elements.
To remove it from the elements of the set, use the ** remove method **. Enter the following code in the ** Python console **. Display the contents of the variable ** S ** once and then execute.
>>> S
{1, 2, 3, 4, 5}
>>> S.remove(2)
>>> S
{1, 3, 4, 5}
You can directly specify and delete the elements of the set.
To delete all the elements of the set, use ** clear method **.
>>> S.clear()
>>> S
set()
If you check the contents of S, ** set () ** will be output. This ** set () ** means an empty set.
You can also check if the set contains the specified element. Use the ** in operator ** with lists and dictionaries.
>>> S = {1, 2, 3, 4}
>>> S
{1, 2, 3, 4}
>>> 2 in S
True
>>> 10 in S
False
This time I touched on the set. You just want to know that the set stores the elements without duplication. Next time, I will touch on set operations and actually implement them on Python.
Recommended Posts