DEV Community

Baransel
Baransel

Posted on

Python Set and Frozenset

What is Set and frozenset?

In our previous Data Types lesson, we divided the data types in Python into mutable (Mutable) and immutable (unchangeable) and here we will process both mutable and immutable data types.

Dictionaries are a little different because Dictionaries consist of two parts; keys and values, value part can contain all data type but keys part can only be of string and int type.

What is Set?

It is a data type that contains multiple data types such as list, dictionary, and tuple data types. You can perform all kinds of functions (joining, intersection, etc.) related to sets with this data type.

Set Usage

Let me show you the use of set with an example;

set = {"Python", 'b', 5, "Baransel"}
Enter fullscreen mode Exit fullscreen mode

It has a very simple usage, but there is something we should pay attention to here if we define an empty set as follows;

set = {}
Enter fullscreen mode Exit fullscreen mode

The interpreter will detect it as a Dictionary. Well, if you ask how to create an empty set, let me show you;

set = set()
Enter fullscreen mode Exit fullscreen mode

we define as.

Let me give another important note about sets: there can be only one element from an element, just like the sets we see here in mathematics. Well, let's see what happens if we try to add;

set = {"Python", 'b', 5, "Baransel", "Python"}

print(set)
# {"Python", 'b', 5, "Baransel"}
Enter fullscreen mode Exit fullscreen mode

Now you will say ok, but we added it, it didn't make any mistakes, but if you say it shows only one of the same ones while showing, let me show you as follows.

set = {"Python", 'b', 5, "Baransel", "Python"}
print(len(set))
# 4
Enter fullscreen mode Exit fullscreen mode

As you can see, when we look at the length of the set, the set sees 4 elements even though we add 5 elements. Since we have given this important note, let me show you how we access the elements of the Set.

Accessing Set Items

Continue this post on my blog! Python Set and Frozenset.

Top comments (1)

Collapse
 
kyle__d40cbed7adbd6a7639 profile image
Kyle .

Dictionaries are a little different because Dictionaries consist of two parts; keys and values, value part can contain all data type but keys part can only be of string and int type.

This is not true, dictionary keys (and set elements) only need to be hashable
For example {False: 0, MyClass: 0, MyClass(): 0} all work.
A very useful pattern with dictionaries is to key with a tuple (which are hashable if all their elements are hashable): {(2, 2): 4, (2, 3): 8, (3, 2): 9}
Please update your blog too, as it is misleading for newbie python developers