I would like to know why this is valid:
set(range(10)) - set(range(5))
but this is not valid:
set(range(10)) + set(range(5))
Is it because '+' could mean both intersection and union?
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Lists are slightly faster than sets when you just want to iterate over the values. Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.
Grouping objects into a set can be useful in programming as well, and Python provides a built-in set type to do so. Sets are distinguished from other object types by the unique operations that can be performed on them.
Python sets don't have an implementation for the +
operator.
You can use |
for set union and &
for set intersection.
Sets do implement -
as set difference. You can also use ^
for symmetric set difference (i.e., it will return a new set with only the objects that appear in one set but do not appear in both sets).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With