Today I'm reading about sets. I knew a few things about sets:

- Sets are mutable, unordered, collections of unique objects

- You can declare an empty set with 'set()'

- You can declare a set with things in it like this: '{1, 2, 2}'

- You can get the difference, union, intersection, etc. like this:

- my_set.thing_I_want(other_set)

- How to create a set comprehension

But there were things I didn't know about sets:

- You don't have to use the .operation() version, you can use operators! Some of which are more intuitive to me than others.

Operation | Equivalent | Result |
---|---|---|

s.issubset(t) | s <= t | test whether every element in
s is in t |

s.issuperset(t) | s >= t | test whether every element in
t is in s |

s.union(t) | s | t | new set with elements from both
s and t |

s.intersection(t) | s & t | new set with elements common to
s and t |

s.difference(t) | s - t | new set with elements in s
but not in t |

s.symmetric_difference(t) | s ^ t | new set with elements in either
s or t but not both |

s.update(t) | s |= t |
return set s with elements
added from t |

s.intersection_update(t) | s &= t |
return set s keeping only
elements also found in t |

s.difference_update(t) | s -= t |
return set s after removing
elements found in t |

s.symmetric_difference_update(t) | s ^= t |
return set s with elements
from s or t but not both |

- There is such a thing as immutable set (it's another class)*

- If you do use the operation_name function version for union, intersection, difference, or symmetric_difference, you don't need to cast the second thing to a set (it just needs to be iterable)

*Edited to add that I've realised it's depreciated and replaced by frozenset since 2.6

## No comments:

## Post a Comment