How to Use Redis ZADD and ZRANGE in Python

Add members to a Redis sorted set with ZADD and retrieve them in score order with ZRANGE in Python.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 12 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

12 lines
Python 3.9+
import redis

client = redis.Redis(host='localhost', port=6379, db=0)

client.delete('scores')

members = {'alice': 30, 'bob': 20, 'carol': 50}
for name, score in members.items():
    client.zadd('scores', {name: score})

result = client.zrange('scores', 0, -1)
print(result)

Output

stdout
['bob', 'alice', 'carol']

How it works

ZADD inserts each member with an associated score into a Redis sorted set. ZRANGE returns members in ascending score order (and lexicographically for ties). The 0, -1 range means from the first to the last element, so the entire set is fetched. The result is a list of member names (bytes by default, though the output shows strings for clarity). This is efficient even for large sets because Redis uses skip lists internally.

Common mistakes

  • Forgetting to delete the key before running again, causing duplicate entries.
  • Passing a tuple (name, score) instead of a dict to ZADD.
  • Assuming ZRANGE returns scores; you need WITHSCORES for that.

Variations

  1. Use `zrevrange(0, -1)` to get elements in descending score order.
  2. Use `zrange(0, -1, withscores=True)` to include scores in the result.

Real-world use cases

  • Leaderboards: store player scores and fetch top players in rank order.
  • Priority queues: process tasks in order of priority stored as scores.
  • Time-series data: use timestamp as score to retrieve recent events.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.