Databases 23 min read

Master Redis Data Types with Python: Strings, Lists, Sets, Sorted Sets, and Hashes

This guide demonstrates how to use Python's redis module to manipulate all major Redis data structures—strings, lists, sets, sorted sets, and hashes—detailing each command, providing clear code examples, and showing expected output for practical learning.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Redis Data Types with Python: Strings, Lists, Sets, Sorted Sets, and Hashes

1. Strings

Python redis module provides the following string operations: SET, GET, GETSET, SETEX, SETNX, MSET, MSETNX, INCR (including INCRBY, DECR, DECRBY), APPEND, SETRANGE, STRLEN.

SET : set(self, name, value, **kwargs)

GET : get(self, name)

GETSET : getset(self, name, value)

SETEX : setex(self, name, value, time)

SETNX : setnx(self, name, value)

MSET : mset(self, mapping)

MSETNX : msetnx(self, mapping)

INCR : incr(self, name, amount=1) – supports INCRBY, DECR, DECRBY via amount

APPEND : append(self, key, value)

SETRANGE : setrange(self, name, offset, value)

STRLEN : strlen(self, name)

Example code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# __author__ = 'Jack'

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.flushall()  # clear Redis

r.setex('name', value='liaogx', time=2)  # set new value with 2s expiration
r.mset(k1='v1', k2='v2', k3='v3')  # batch set
print(r.mget('k1', 'k2', 'k3', 'k4'))  # batch get
print(r.getset('name', 'liaogaoxiang'))  # set new value and get old
print(r.getrange('name', 0, 1))  # get substring
r.setrange('name', 0, 'LIAO')  # modify string from offset

i = 0
while i < 4:
    print(r.get('name'))
    time.sleep(1)
    i += 1
source = 'foo'
r.set('n1', source)
r.setbit('n1', 7, 1)
print(r.get('n1'))
print(r.getbit('n1', 7))
r.set('n2', '廖高祥')
print(r.strlen('n2'))
r.set('num', 1)
r.incr('num', amount=10)
r.decr('num', amount=1)
print(r.get('num'))
r.append('num', 111)
print(r.get('num'))

Output:

[b'v1', b'v2', b'v3', None]
b'liaogx'
b'li'
b'LIAOgaoxiang'
b'LIAOgaoxiang'
b'LIAOgaoxiang'
b'LIAOgaoxiang'
b'goo'
1
9
b'10'
b'10111'

2. Lists

Redis list commands are wrapped by the redis module as: LPUSH, LRANGE, LINDEX, BLPOP, BRPOP. Functions are described below.

LPUSH lpush key value – push value to the head of the list.

LRANGE lrange key start end – get elements in the specified range.

LINDEX lindex key index – get element by index.

BLPOP – pop first element from the left (blocking).

BRPOP – pop first element from the right (blocking).

LPUSHX, RPUSHX – not implemented in the current version.

Example code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# __author__ = 'Jack'

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.flushall()

r.lpush('oo', 11)  # list becomes: 11
r.lpushx('oo', 0)  # only works if list exists
print(r.llen('oo'))  # length

r.linsert('oo', 'before', 11, 99)  # insert 99 before 11
r.lset('oo', 1, 88)  # set index 1 to 88
print(r.lrange('oo', 0, -1))

r.lrem('oo', 88, num=1)  # remove one occurrence of 88
print(r.lrange('oo', 0, -1))

print(r.lpop('oo'))  # pop leftmost element
print(r.lindex('oo', 0))

r.lpush('l1', 11)
r.rpush('l1', 22)
r.rpush('l1', 33)
r.rpush('l1', 44)
r.rpush('l1', 55)
r.ltrim('l1', 1, 3)  # keep indices 1‑3
print(r.lrange('l1', 0, -1))

r.rpoplpush('l1', 'l1')
print(r.lrange('l1', 0, -1))

r.brpoplpush('l1', 'l1', timeout=3)
print(r.lrange('l1', 0, -1))

print(r.blpop('l1', 3))
print(r.lrange('l1', 0, -1))

def list_iter(name):
    list_count = r.llen(name)
    for index in range(list_count):
        yield r.lindex(name, index)

for item in list_iter('l1'):
    print(item)

Output (excerpt):

2
[b'0', b'88', b'11']
[b'0', b'11']
b'0'
b'11'
[...]

3. Sets

Redis set commands are wrapped as: SADD, SCARD, SDIFF, SDIFFSTORE, SINTER, SINTERSTORE, SISMEMBER, SMEMBERS, SMOVE, SPOP, SRANDMEMBER, SREM, SUNION, SUNIONSTORE, SSCAN.

SADD : sadd(self, name, value)

SCARD : scard(self, name)

SDIFF : sdiff(self, keys, *args)

SDIFFSTORE : sdiffstore(self, dest, keys, *args)

SINTER : sinter(self, keys, *args)

SINTERSTORE : sinterstore(self, dest, keys, *args)

SISMEMBER : sismember(self, name, value)

SMEMBERS : smembers(self, name)

SMOVE : smove(self, src, dest, value)

SPOP : spop(self, name)

SRANDMEMBER : srandmember(self, name)

SREM : srem(self, name, value)

SUNION : sunion(self, keys, *args)

SUNIONSTORE : sunionstore(self, dest, keys, *args)

SSCAN : sscan(self, name, cursor=0, match=None, count=None)

Example code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# __author__ = 'Jack'

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.flushall()

r.sadd('s1', 'v1', 'v1', 'v2', 'v3')
r.sadd('s2', 'v2', 'v4')
print(r.scard('s1'))
print(r.sdiff('s1', 's2'))

r.sdiffstore('s3', 's1', 's2')
print(r.smembers('s3'))

print(r.sinter('s1', 's2'))
r.sinterstore('s4', 's1', 's2')
print(r.smembers('s4'))

print(r.sunion('s1', 's2'))

r.sunionstore('s5', 's1', 's2')
print(r.smembers('s5'))

print(r.sismember('s4', 'v4'))

r.smove('s2', 's1', 'v4')
print(r.smembers('s1'))

r.srem('s1', 'v1')
print(r.spop('s1'))
print(r.srandmember('s1'))

Output (excerpt):

3
{b'v3', b'v1'}
{b'v3', b'v1'}
{b'v3', b'v1'}
{b'v3', b'v2', b'v4', b'v1'}
False
{b'v3', b'v2', b'v4', b'v1'}
b'v2'
b'v2'

4. Sorted Sets

Redis sorted‑set commands include ZADD, ZCARD, ZCOUNT, ZINCRBY, ZINTERSTORE, ZLEXCOUNT, ZRANGE, ZRANGEBYLEX, ZRANGEBYSCORE, ZRANK, ZREM, ZREMRANGEBYLEX, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREVRANGE, ZREVRANGEBYSCORE, ZREVRANK, ZSCORE, ZUNIONSTORE, ZSCAN.

Example code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# __author__ = 'Jack'

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.flushall()

r.zadd('z1', '11', 1, '22', 2, '33', 3, '44', 4, '55', 5, '66', 6, '66', 7)
print(r.zcard('z1'))
print(r.zcount('z1', 1, 2))
r.zincrby('z1', '11', amount=5)
print(r.zrange('z1', 0, -1, desc=False, withscores=True))

print(r.zrank('z1', 33))

r.zrem('z1', '66')
print(r.zrange('z1', 0, -1, desc=False, withscores=True))

r.zremrangebyrank('z1', 0, 1)
print(r.zrange('z1', 0, -1, desc=False, withscores=True))

r.zremrangebyscore('z1', 4.5, 5.5)
print(r.zrange('z1', 0, -1, desc=False, withscores=True))

print(r.zscore('z1', 11))

r.zadd('zset_name', 'a1', 6, 'a2', 2, 'a3', 5)
r.zadd('zset_name1', a1=7, b1=10, b2=5)
r.zinterstore('zset_name2', ('zset_name', 'zset_name1'), aggregate='Sum')
print(r.zrange('zset_name2', 0, -1, desc=False, withscores=True))

Output (excerpt):

6
2
[(b'22', 2.0), (b'33', 3.0), (b'44', 4.0), (b'55', 5.0), (b'11', 6.0), (b'66', 6.0)]
1
[(b'22', 2.0), (b'33', 3.0), (b'44', 4.0), (b'55', 5.0), (b'11', 6.0)]
[(b'44', 4.0), (b'55', 5.0), (b'11', 6.0)]
[(b'44', 4.0), (b'11', 6.0)]
6.0
[(b'a1', 13.0)]

5. Hashes

Redis hash commands are wrapped as: HDEL, HEXISTS, HGET, HGETALL, HINCRBY, HKEYS, HLEN, HMGET, HMSET, HSET, HSETNX, HVALS, HINCRBYFLOAT.

HDEL : hdel(self, name, key)

HEXISTS : hexists(self, name, key)

HGET : hget(self, name, key)

HGETALL : hgetall(self, name)

HINCRBY : hincrby(self, name, key, amount=1)

HKEYS : hkeys(self, name)

HLEN : hlen(self, name)

HMGET : hmget(self, name, keys)

HMSET : hmset(self, name, mapping)

HSET : hset(self, name, key, value)

HSETNX : hsetnx(self, name, key, value)

HVALS : hvals(self, name)

HINCRBYFLOAT : hincrbyfloat(self, name, key, amount=1.0)

Example code:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# __author__ = 'Jack'

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
r.flushall()

r.hset('n1', 'k1', 'v1')
print(r.hget('n1', 'k1'))

r.hmset('n2', {'k1':'v1','k2':'v2','k3':'v3'})
print(r.hmget('n2', 'k2'))
print(r.hgetall('n2'))
print(r.hlen('n2'))
print(r.hkeys('n2'))
print(r.hvals('n2'))
print(r.hexists('n2', 'k4'))

r.hdel('n2', 'k3')

r.hset('n3', 'k1', 1)
r.hincrby('n3', 'k1', amount=1)
print(r.hgetall('n3'))

Output:

b'v1'
[b'v2']
{b'k1': b'v1', b'k2': b'v2', b'k3': b'v3'}
3
[b'k1', b'k2', b'k3']
[b'v1', b'v2', b'v3']
False
{b'k1': b'2'}

For a complete reference of Redis commands, see the official Redis documentation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonredisData Types
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.