Skip to content

Step 1 of 3 · Reading · ~2 min

Redis Sets

Sets & Sorted Sets

Sets: uniqueness for free

A Redis set is an unordered collection of unique members — think "tags on a post" or "unique visitors today." The entire value proposition is that membership tests and duplicate elimination are O(1), which maps directly onto Python's built-in set.

The underlying structure

python

Because set.add on an already-present member is a silent no-op, you might be tempted to just do before = len(s); s.update(members); return len(s) - before. That works too and is simpler — either approach is fine, but understand why both give the same answer: set semantics guarantee no duplicates land in the structure regardless of how many times you add the same value.

SADD's return value

Like HSET, SADD returns the count of genuinely new members, not the number of arguments passed. SADD tags red red blue against an empty set returns 2 (red counted once, blue once) — the repeated red in the same call doesn't count twice either, since after the first red is added the second is no longer new.

SISMEMBER and SCARD

python

Both reply as RESP integers. SISMEMBER on a missing key isn't an error — it's simply 0, the same as asking "is X a member of the empty set," which is always false.

SREM and cleanup

python

Same auto-delete pattern you've now seen for lists and hashes: an empty set is not a valid stored value, so once the last member is removed the key vanishes.

SMEMBERS and why the lesson says "we'll sort"

SMEMBERS returns every member as a RESP array. Because Python's set has no defined iteration order (and Redis itself doesn't guarantee member order either), a naive test that checks the array literally would be flaky. The test harness for this exercise sorts both sides before comparing — so don't worry about matching Redis's internal ordering, just return every member exactly once. This is also a good moment to note: sets store unique elements, but element identity is by exact string equality"1" and "01" are different members, not the same number.

Up nextZADD, ZSCORE & ZRANGE — Sorted SetsSets & Sorted Sets

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…