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:

  1. iterable (optional): objects can be string, tuple, set, list, dictionary. .or iterator object .

The value returned from set

  1. If no parameters are passed, set () creates an empty set.
  2. 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