Python Set
In Python set is almost similar to dictionary. A set is dictionary with no values. As described in dictionary chapter, dictionary data type work with key – value pairs as shown below:
dictionary_name = {key:value, key:value, …..}
Whereas set works like this:
set_name = {key1, key2, …..}
Practically set is used less in Python. Uses may include removing duplicates from a sequence, testing of membership, a few mathematical operations like difference, symmetric difference, union etc.
Example of using set
The example below creates a set with four keys. Two are given same name. Next statement will print set.
1
2
3
4
5
|
#create a set
set_items = {“emp_name”,“emp_salary”,“emp_address”,“emp_name”}
print (set_items)
|
The output will be:
{’emp_salary’, ’emp_address’, ’emp_name’}
As you can see duplicate keys are printed.
Getting length of set
1
2
3
4
5
6
7
|
#create a set
set_items = {“emp_name”,“emp_salary”,“emp_address”,“emp_name”}
print (set_items)
print (len(set_items))
|
The output will be:
{’emp_name’, ’emp_salary’, ’emp_address’}
3
Length is 3, as duplicate key is omitted.
Leave A Comment?