set() Function in Python Examples
Below are the ways by which we can use set() in Python:
- Creating an Empty Set
- Using set() with List
- Using set() with Tuples
- Creating set with Range
- Converting Dictionary into a Set
Creating a Set by using set() Function
In this example, we are creating a Set using set() function.
Python3
# we are creating an #empty set by using set() s = set () print ( "Type of s is " , type (s)) |
Type of s is <class 'set'>
set() Function with List
In this example, we are using set() with List. Here, we will convert an iterable to a sequence with unique elements in Python.
Python3
# working of set() on list # initializing list lis1 = [ 3 , 4 , 1 , 4 , 5 ] # Printing iterables before conversion print ( "The list before conversion is : " + str (lis1)) # Iterables after conversion are # notice distinct and elements print ( "The list after conversion is : " + str ( set (lis1))) |
The list before conversion is : [3, 4, 1, 4, 5] The list after conversion is : {1, 3, 4, 5}
set() Function with Tuple
In this example, we are using set() function with tuple.
Python3
# working of set() on tuple # initializing tuple tup1 = ( 3 , 4 , 1 , 4 , 5 ) # Printing iterables before conversion print ( "The tuple before conversion is : " + str (tup1)) # Iterables after conversion are # notice distinct and elements print ( "The tuple after conversion is : " + str ( set (tup1))) |
The tuple before conversion is : (3, 4, 1, 4, 5) The tuple after conversion is : {1, 3, 4, 5}
set() Function with Range
In this example, we are using set() function with range function. Here, we will convert an iterable to a sequence with unique elements in Python.
Python3
# working of set() on range # initializing range r = range ( 5 ) r = set (r) # Iterables after conversion are # notice distinct and elements print ( "The Range after conversion is : " + str (r)) |
The Range after conversion is : {0, 1, 2, 3, 4}
Demonstration of set() Method with Dictionary
In this example, we are seeing the demonstration of set() with Dictionary and it’s working.
Python3
# Python3 code to demonstrate the # working of set() on dictionary # initializing list dic1 = { 4 : 'geeks' , 1 : 'for' , 3 : 'geeks' } # Printing dictionary before conversion # internally sorted print ( "Dictionary before conversion is : " + str (dic1)) # Dictionary after conversion are # notice lost keys print ( "Dictionary after conversion is : " + str ( set (dic1))) |
Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'} Dictionary after conversion is : {1, 3, 4}
Python | set() Function
set() method is used to convert any of the iterable to a sequence of iterable elements with distinct elements, commonly called Set. In Python, the set() function is a built-in constructor that is used to initialize a set or create an empty. In this article, we will see about set() in Python and how we can convert an iterable to a sequence with unique elements in Python.
Contact Us