Retrieving values trimmed by ltrim in redis list
<p>A common design pattern in redis when handling lists is:</p>

<pre><code>redis_server.lpush(list_name, element)
redis_server.ltrim(list_name, 0, 99)
</code></pre>

<p>(used python syntax to illustate it)</p>

<p>What to do if one needs to retrieve all the values beyond index 99, before invoking <code>ltrim</code>? One way to do it is as follows, but is there a <em>faster</em> way to do it?</p>

<hr>

<pre><code>redis_server.lpush(list_name, element)
list_length = redis_server.llen(list_name)
extra = list_length - 100
while (extra &gt; 0):
    item = redis_server.lpop(list_name)
    #do something with the item
    extra = extra - 1
redis_server.ltrim(list_name, 0, 99)
</code></pre>

<p>A first solution would be to get all extra items in one request, using <a href="http://redis.io/commands/lrange" rel="nofollow">LRANGE</a>:</p>

<p><code>
    redis_server.lpush(list_name, element)
    items = redis_server.lrange(list_name, 100, -1)
    # do something with the items
    redis_server.ltrim(list_name, 0, 99)
</code></p>

<p>A second solution, a bit more complex but <em>maybe</em> faster (would need to be confirmed by a test, it's not certain) as it requires only one request instead of two, would be to write a Lua script and to send it using <a href="http://redis.io/commands/eval" rel="nofollow">EVAL</a> and <a href="http://redis.io/commands/evalsha" rel="nofollow">EVALSHA</a>. But you probably don't need it, the first is certainly fast enough.</p>

python redis