| Start | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Operations on sets with other sets with single elements Set operations return new sets, but have the corresponding in-place versions:
For example: |
|||||||||||||||
| Get the unique elements of a list Let's say you've got a list of restaurants -- maybe you read it from a file. You care about the unique restaurants in the list. The best way to get the unique elements from a list is to turn it into a set: Note that the set is not in the same order as the original list; that is because sets are unordered, just like This can easily be transformed back into a It's also common to see this as one line: Now any operations that could be performed on the original list can be done again. |
|||||||||||||||
Set of Sets leads to: Instead, use |
|||||||||||||||
| Set Operations using Methods and Builtins We define two sets NOTE: Intersection
Union
Difference
Symmetric Difference
NOTE: Subset and superset
The latter operations have equivalent operators as shown below:
Disjoint setsSets Testing membershipThe builtin LengthThe builtin |
|||||||||||||||
| Sets versus multisets Sets are unordered collections of distinct elements. But sometimes we want to work with unordered collections of elements that are not necessarily distinct and keep track of the elements' multiplicities. Consider this example: By saving the strings but a list data structure introduces an extra unneeded ordering that will slow down our computations. For implementing multisets Python provides the
Syntax
RemarksSets are unordered and have very fast lookup time (amortized O(1) if you want to get technical). It is great to use when you have a collection of things, the order doesn't matter, and you'll be looking up items by name a lot. If it makes more sense to look up items by an index number, consider using a list instead. If order matters, consider a list as well. Sets are mutable and thus cannot be hashed, so you cannot use them as dictionary keys or put them in other sets, or anywhere else that requires hashable types. In such cases, you can use an immutable The elements of a set must be hashable. This means that they have a correct |
Read Article
https://develop.horje.com/learn/1434/reference