The function set () in Python
In this article, TipsMake.com will learn with you about set (), syntax, parameters and specific examples. Invites you to read the track.
The set () function built into Python is used to create a set object from the given iterable.
In this article, TipsMake.com will learn with you about set (), syntax, parameters and specific examples. Invites you to read the track.
Syntax of set () function in Python
set([iterable])
Parameters of the set () function
Python's set () constructor has a single parameter:
iterable
(optional): objects can be string, tuple, set, list, dictionary. .or iterator object .
The value returned from set
- If no parameters are passed, set () creates an empty set.
- If iterable is passed as a parameter, it will create a set of elements in iterable.
Example 1: Create a collection from string, tuple, list, range
# tập hợp rỗng print(set()) # string print(set('Python')) # tuple # viết bởi TipsMake.com print(set(('a', 'e', 'i', 'o', 'u'))) # list print(set(['a', 'e', 'i', 'o', 'u'])) # range print(set(range(5)))
Running the program, the result is returned:
set() {'P', 'o', 't', 'n', 'y', 'h'} {'a', 'o', 'e', 'u', 'i'} {'a', 'o', 'e', 'u', 'i'} {0, 1, 2, 3, 4}
Example 2: Create a collection from set, dictionary and frozen set
# set print(set({'a', 'e', 'i', 'o', 'u'})) # dictionary # viết bởi TipsMake.com print(set({'a':1, 'e': 2, 'i':3, 'o':4, 'u':5})) # frozen set frozenSet = frozenset(('a', 'e', 'i', 'o', 'u')) print(set(frozenSet))
Running the program results in:
{'a', 'o', 'i', 'e', 'u'} {'a', 'o', 'i', 'e', 'u'} {'a', 'o', 'e', 'u', 'i'}
Example 3: Creating a collection from an iterator object
class PrintNumber: def __init__(self, max): self.max = max def __iter__(self): self.num = 0 return self def __next__(self): if(self.num >= self.max): raise StopIteration self.num += 1 return self.num printNum = PrintNumber(5) # tạo set # viết bởi TipsMake.com print(set(printNum))
Running the program results in:
{1, 2, 3, 4, 5}
See also: Python built-in functions
Update 04 September 2019
You should read it
- The map () function in Python
- The next () function in Python
- Max () function in Python
- The oct () function in Python
- The pow () function in Python
- The slice () function in Python
- The function id () in Python
- Min () function in Python
- Zip () function in Python
- Int () function in Python
- The ord () function in Python
- List () function in Python
Maybe you are interested
How to Communicate Well With People from Other Cultures What does the 'super slow' 7680fps movie recording feature on the Mate 30 Pro do? Hitman Sniper famous game is being free on iOS and Android How to create slow motion videos on Android? 8 ways to win people's hearts 6 tips to help you get out of debt