Containers

Sets

In [33]:
S = {10, 3, 7, 2, 11}
S
Out[33]:
{2, 3, 7, 10, 11}
In [34]:
T = {5, 4, 5, 2, 4, 9}
T
Out[34]:
{2, 4, 5, 9}
In [35]:
L = [10, 13, 10, 5, 6, 13, 2, 10, 5]
S2 = set(L)
S2
Out[35]:
{2, 5, 6, 10, 13}
In [36]:
# Union (Elements in S or T or both)

S | T
Out[36]:
{2, 3, 4, 5, 7, 9, 10, 11}
In [37]:
# Intersection (Elements common to both S and T)

S & T
Out[37]:
{2}
In [38]:
# Set Difference (Elements in S but not in T)

S - T
Out[38]:
{3, 7, 10, 11}
In [39]:
# Symmetric Difference (Elements in S or T, but not both)

S ^ T
Out[39]:
{3, 4, 5, 7, 9, 10, 11}
In [40]:
# Set Membership

3 in S
Out[40]:
True
In [41]:
# Set Membership

3 not in S
Out[41]:
False
In [42]:
# Set Equality (Sets S and T contain exactly the same elements)

S == T
Out[42]:
False
In [43]:
# Subset (Every element in set T also is a member of set S)

T <= S
Out[43]:
False
In [44]:
# Proper subset (A is a subset B, but B contains at least one element not in A)

T < S
Out[44]:
False
In [45]:
# add() for enkelt-elementer
# update() for lister av nye elementer

fruitset = {"apple", "banana", "cherry", "durian", "mango"}
print(fruitset)
fruitset.add("apple")
fruitset.add("elderberry")
print(fruitset)
fruitset.update(["apple","apple","apple","strawberry","strawberry","apple","mango"])
print(fruitset)
{'mango', 'cherry', 'apple', 'banana', 'durian'}
{'mango', 'cherry', 'apple', 'elderberry', 'banana', 'durian'}
{'mango', 'cherry', 'apple', 'elderberry', 'banana', 'strawberry', 'durian'}
In [46]:
# remove()

fruitset = {"apple", "banana", "cherry", "durian", "mango"}
print(fruitset)
fruitset.remove("apple")
print(fruitset)
{'mango', 'cherry', 'apple', 'banana', 'durian'}
{'mango', 'cherry', 'banana', 'durian'}