Set

Set

Mutable collection data type. Set can be modified.
Set has unique features:
Set does not contain duplicate elements, every element in a set is unique
Membership testing against a set (search if a value is an element of a set) is hashmap, meaning search against a set is faster than against a list, which is linear search.
Example:
s={1,2,3,4,5,5}
You notice there are two 5s
When you print out s, you only see one 5, which is
{1, 2, 3, 4, 5}
You can convert a list to a set by using function set(), by doing so, you eliminate duplicate elements
l=[1,2,3,4,5,5]
set(l)
l=[1,2,3,4,5,5]
set(l)
{1, 2, 3, 4, 5}
To create an empty set, use function set()
s=set()
To add an element β€˜a’ into s:
s.add(β€˜a’)
To delete element β€˜a’ from s:
s.remove(β€˜a’)
Need to note:
Order of elements in a set is not guaranteed and consistent
Last modified 1yr ago
Copy link