Data type set
in python
set
is a collection of unique valuse, which is quite common in deduplicating or testing membership. It’s just like a dictoniry but with only keys and not values. The API is pretty much the same, but operation like indexing and slicing is not supported.
a = set([1,2,3,1])
b = set([2,3,4])
a
{1, 2, 3}
print b
set([2, 3, 4])
Common operations
a
{1, 2, 3}
len(a)
3
2 in a
True
Loop through
# like looping through dictoniry
for i in a:
print i,
1 2 3
Add
a.add(4)
a
{1, 2, 3, 4}
Remove
# a.remove(el), if not found, raise error
a.remove(4)
a
{1, 2, 3}
# a.discard(el), if not found, do nothing
a.discard(4)
pop
a.pop()
1
a
{2, 3}
Intersection
a.intersection(b)
{2, 3}
Difference
# a - b
a.difference(b)
set()
# b - a
b.difference(a)
{4}
Sub or Super set
a.issubset(b)
True
b.issuperset(a)
True
Clear
a.clear()
a
set()