Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The most common set operations you’ll likely encounter are the
union, intersection, and difference operations. Recall that the
difference between a set and a list is that a set is unordered and
contains only unique members, while a list is ordered and may contain
duplicate members. As of Version 2.6, Python provides built-in support
for sets via the set data structure.
Table 4-1 illustrates
some examples of common set operations for a trivially small universe of
discourse involving friends and followers:
Friends = {Abe, Bob}, Followers = {Bob, Carol}Table 4-1. Sample set operations for Friends and Followers
| Operation | Result | Comment |
|---|---|---|
Friends ?
Followers | Abe, Bob,
Carol | Someone’s overall network |
Friends n
Followers | Bob | Someone’s mutual friends |
Friends –
Followers | Abe | People a person is following, but who are not following that person back |
Followers –
Friends | Carol | People who are following someone but are not being followed back |
As previously mentioned, Redis provides native operations for computing common set operations. A few of the most relevant ones for the upcoming work at hand include:
smembersReturns all of the members of a set
scardReturns the cardinality of a set (the number of members in the set)
sinterComputes the intersection for a list of sets
sdiffComputes the difference for a list of sets
mgetReturns a list of string values for a list of keys
msetStores a list of string values against a list of keys
saddAdds an item to a set (and creates the set if it doesn’t already exist)
keysReturns a list of keys matching a regex-like pattern
Skimming the pydoc for Python’s built-in set data type should convince you of the close mapping between it and the Redis APIs.