The Python set function is used to create sets out of data passed into it’s parameters. Typically this data is in the form of an iterable such as a string or list, which is then converted into set format.
The syntax of the set function is as follows
set(iterable)
where iterable is a valid data type, such as lists or tuples or an iterator object. If no parameters were passed, the set function will return an empty set.
Example 1:
In the example below we explore two cases of the set function. The first creates an empty set by calling the set function with no parameters. The second takes a string as input. However, the output is missing a character. This is because Data in sets must be unique. And the reason for the data being in such a strange order is because data in sets is unordered. If you repeat the same function over and over, you’ll see different results.
>>> set()
set()
>>> set("Hello")
{'e', 'l', 'o', 'H'}
Example 2:
We’ll explore some more typical cases here such as lists, dictionaries and tuples.
>>> set([1,2,3,4,5])
{1, 2, 3, 4, 5}
>>> set((1,2,3,4,5))
{1, 2, 3, 4, 5}
>>> set({1:"a", 2:"b", 3:"c"})
{1, 2, 3}
With dictionaries, only the keys are placed into the set, and the values are ignored.
This marks the end of the Python set Function section. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions be can be directed to the comments section below.