Redis Command: LRANGE

Summary

Command NameLRANGE
UsageGet items from list
Group list
ACL Category@read
@string
@slow
Time ComplexityO(S+N)
FlagREADONLY
Arity4

Notes

  • Time complexity of the command is O(S+N). Here S is the distance of the starting index/offset from HEAD/TAIL of the list and N is the number of elements to be returned.
    • For a small list, the distance(S) is calculated from the HEAD/Left end of the list.
    • For a large list, the distance(S) is calculated from whichever end is closer to the starting index. If the starting index/offset is closer to the HEAD/Left end then it is calculated from the left end. Otherwise, the first offset distance is calculated from the TAIL/Right end of the list.

Signature

LRANGE <key> <start_index> <stop_index>

Usage

Retrieve items from a list. This command gets the items of a list by start and end indexes. This is the most used command for checking and fetching items from a list.

Redis List example with index
Redis List example with index

Notes

  • To retrieve all the items from the list use start_index=0 and stop_index=-1. Like below-
    LRANGE mysimplelist 0 -1

Arguments

ParameterDescriptionNameType
<key>Name of the key of the listkeykey
<start_index>Start index of the list, from where we want to start our desired result list.startinteger
<stop_index>Last index of the list, to which we want to end our desired result liststopinteger

Notes

  • Indexes are Zero(0) based. So the first item of the list is considered index Zero(0)
  • The indexes can be counted in reverse also. In that case the last item is at index -1.

Return Value

Return valueCase for the return valueType
List of elementsWhen the operation is valid, then the list of elements is returned from the list.array[string]
Empty listWhen the list does not exist
or the starting index is larger than the ending index
(empty array)
errorIf data is not of string typeerror

Notes

  • Item at the start and stop index are inclusive. That means those items are included and returned in the result.
  • As zero-based index is used. So if we provided star_index=0 and stop_index=6, then total Seven(7) items are returned.

Examples

Here are a few examples of the LRANGE command usage-

# Redis LRANGE command examples

# Create list with 8 items
127.0.0.1:6379> rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
(integer) 8

# Get item from list from start to the 5th index
127.0.0.1:6379> lrange simplelist 0 5
1) "first item"
2) "second item"
3) "third"
4) "fourth"
5) "fifth"
6) "sixth"

# Get list items from start to the end(all items)
127.0.0.1:6379> lrange simplelist 0 -1
1) "first item"
2) "second item"
3) "third"
4) "fourth"
5) "fifth"
6) "sixth"
7) "seventh"
8) "eighth"

# Get list items from 5th index to the end of list
127.0.0.1:6379> lrange simplelist 5 -1
1) "sixth"
2) "seventh"
3) "eighth"

# Get list items from 5th index(from end) to the last item
127.0.0.1:6379> lrange simplelist -5 -1
1) "fourth"
2) "fifth"
3) "sixth"
4) "seventh"
5) "eighth"

# Try to get list items with starting index larger that end index
# We get an empty list
127.0.0.1:6379> lrange simplelist 3 1
(empty array)

# When the provided index is out of range, then the command adjusts to the starting or ending index
127.0.0.1:6379> lrange simplelist 5 10000
1) "sixth"
2) "seventh"
3) "eighth"

# If range is out of range then it is adjusted with the actual index
127.0.0.1:6379> lrange simplelist -99 999
1) "first item"
2) "second item"
3) "third"
4) "fourth"
5) "fifth"
6) "sixth"
7) "seventh"
8) "eighth"

# Get items from index -5 to 4
127.0.0.1:6379> lrange simplelist -5 4
1) "fourth"
2) "fifth"

# Try to get items from a list that does not exist
# We get an empty array
127.0.0.1:6379> lrange wronglist 0 -1
(empty array)

# Set a string value
127.0.0.1:6379> set keyone "some value for key one"
OK

# Try to use LRANGE for an element that is not a list
# We get an error for WRONGTYPE
127.0.0.1:6379> lrange keyone 0 -1
(error) WRONGTYPE Operation against a key holding the wrong kind of value

# Pass non integer index
# We get an error
127.0.0.1:6379> lrange simplelist some_string_here 5
(error) ERR value is not an integer or out of range

Notes

  • If we provide a key to LRANGE that does not exist, then we get an empty array-
    (empty array)
  • If the starting index is larger than the end index then we get an empty array-
    (empty array)
  • If the starting index is out of range(larger than list length), then empty array is returned-
    (empty array)
  • If the provided key is not a list then the following error is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value
  • If the provided indexes are not valid integers then we get the following error-
    (error) ERR value is not an integer or out of range
  • If the provided indexes are out of range then the indexes are adjusted to the start and/or end of the list index.

Code Implementations

Here are the usage examples of the Redis LRANGE command in different programming languages.

// Redis LRANGE command example in Golang

package main

import (
	"context"
	"fmt"

	"github.com/redis/go-redis/v9"
)

var rdb *redis.Client
var ctx context.Context

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Username: "default",
		Password: "",
		DB:       0,
	})

	ctx = context.Background()
}

func main() {

	// Create list with 8 items
	// Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
	// Result: (integer) 8
	listCreateResult, err := rdb.RPush(ctx, "simplelist", "first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth").Result()

	if err != nil {
		fmt.Printf("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: %dn", listCreateResult)
	}

	fmt.Printf("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: %dn", listCreateResult)

	// Get item from list from start to the 5th index
	// Command: lrange simplelist 0 5
	// Result:
	//      1) "first item"
	//      2) "second item"
	//      3) "third"
	//      4) "fourth"
	//      5) "fifth"
	//      6) "sixth"
	lrangeResult, err := rdb.LRange(ctx, "simplelist", 0, 5).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist 0 5 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist 0 5 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Get list items from start to the end(all items)
	// Command: lrange simplelist 0 -1
	// Result:
	//      1) "first item"
	//      2) "second item"
	//      3) "third"
	//      4) "fourth"
	//      5) "fifth"
	//      6) "sixth"
	//      7) "seventh"
	//      8) "eighth"
	lrangeResult, err = rdb.LRange(ctx, "simplelist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist 0 -1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Get list items from 5th index to the end of list
	// Command: lrange simplelist 5 -1
	// Result:
	//      1) "sixth"
	//      2) "seventh"
	//      3) "eighth"

	lrangeResult, err = rdb.LRange(ctx, "simplelist", 5, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist 5 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist 5 -1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Get list items from 5th index(from end) to the last item
	// Command: lrange simplelist -5 -1
	// Result:
	//      1) "fourth"
	//      2) "fifth"
	//      3) "sixth"
	//      4) "seventh"
	//      5) "eighth"
	lrangeResult, err = rdb.LRange(ctx, "simplelist", -5, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist -5 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist -5 -1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Try to get list items with starting index larger that end index
	// We get an empty list
	// Command: lrange simplelist 3 1
	// Result: (empty array)
	lrangeResult, err = rdb.LRange(ctx, "simplelist", 3, 1).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist 3 1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist 3 1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// When the provided index is out of range, then the command adjusts to the starting or ending index
	// Command: lrange simplelist 5 10000
	// Result:
	//      1) "sixth"
	//      2) "seventh"
	//      3) "eighth"
	lrangeResult, err = rdb.LRange(ctx, "simplelist", 5, 10_000).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist 5 10000 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist 5 10000 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// If range is out of range then it is adjusted with the actual index
	// Command: lrange simplelist -99 999
	// Result:
	//      1) "first item"
	//      2) "second item"
	//      3) "third"
	//      4) "fourth"
	//      5) "fifth"
	//      6) "sixth"
	//      7) "seventh"
	//      8) "eighth"
	lrangeResult, err = rdb.LRange(ctx, "simplelist", -99, 999).Result()

	if err != nil {
		fmt.Println("Command: lrange simplelist -99 999 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange simplelist -99 999 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Try to get items from a list that does not exist
	// We get an empty array
	// Command: lrange wronglist 0 -1
	// Result: (empty array)
	lrangeResult, err = rdb.LRange(ctx, "wronglist", 0, -1).Result()

	if err != nil {
		fmt.Println("Command: lrange wronglist 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange wronglist 0 -1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

	// Set a string value
	// Command: set keyone "some value for key one"
	// Result: OK
	setResult, err := rdb.Set(ctx, "keyone", "some value for key one", 0).Result()

	if err != nil {
		fmt.Println("Command: set keyone "some value for key one" | Error: " + err.Error())
	}

	fmt.Println("Command: set keyone "some value for key one" | Result:" + setResult)

	// Try to use LRANGE for an element that is not a list
	// We get an error for WRONGTYPE
	// Command: lrange keyone 0 -1
	// Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	lrangeResult, err = rdb.LRange(ctx, "keyone", 0, 5).Result()

	if err != nil {
		fmt.Println("Command: lrange keyone 0 -1 | Error: " + err.Error())
	}

	fmt.Println("Command: lrange keyone 0 -1 | Result:")

	for _, val := range lrangeResult {
		fmt.Println(val)
	}

}

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:
first item
second item
third
fourth
fifth
sixth

Command: lrange simplelist 0 -1 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 5 -1 | Result:
sixth
seventh
eighth

Command: lrange simplelist -5 -1 | Result:
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 3 1 | Result:

Command: lrange simplelist 5 10000 | Result:
sixth
seventh
eighth

Command: lrange simplelist -99 999 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange wronglist 0 -1 | Result:

Command: set keyone "some value for key one" | Result:OK
Command: lrange keyone 0 -1 | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: lrange keyone 0 -1 | Result:

Notes

  • Use “LRange” method from redis-go module.
  • Signature of the method is-
    LRange(ctx context.Context, key string, start, stop int64) *StringSliceCmd
// Redis LRANGE command example in JavaScript(NodeJS)

import { createClient } from 'redis';

// Create redis client
const redisClient = createClient({
    url: 'redis://default:@localhost:6379'
});

redisClient.on('error', err => console.log('Error while connecting to Redis', err));

// Connect Redis client
await redisClient.connect();

/**
 * Create list with 8 items
 *
 * Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
 * Result: (integer) 8
 */
let commandResult = await redisClient.rPush("simplelist", ["first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]);

console.log("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: " + commandResult);

/**
 * Get item from list from start to the 5th index
 *
 * Command: lRange simplelist 0 5
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 */
commandResult = await redisClient.lRange("simplelist", 0, 5);

console.log("Command: lRange simplelist 0 5 | Result:", commandResult);

/**
 * Get list items from start to the end(all items)
 *
 * Command: lRange simplelist 0 -1
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 *      7) "seventh"
 *      8) "eighth"
 */
commandResult = await redisClient.lRange("simplelist", 0, -1);

console.log("Command: lRange simplelist 0 -1 | Result:", commandResult);

/**
 * Get list items from 5th index to the end of list
 *
 * Command: lRange simplelist 5 -1
 * Result:
 *      1) "sixth"
 *      2) "seventh"
 *      3) "eighth"
 */
commandResult = await redisClient.lRange("simplelist", 5, -1);

console.log("Command: lRange simplelist 5 -1 | Result:", commandResult);

/**
 * Get list items from 5th index(from end) to the last item
 *
 * Command: lRange simplelist -5 -1
 * Result:
 *      1) "fourth"
 *      2) "fifth"
 *      3) "sixth"
 *      4) "seventh"
 *      5) "eighth"
 */
commandResult = await redisClient.lRange("simplelist", -5, -1);

console.log("Command: lRange simplelist -5 -1 | Result:", commandResult);

/**
 * Try to get list items with starting index larger that end index
 * We get an empty list
 * Command: lRange simplelist 3 1
 * Result: (empty array)
 */
commandResult = await redisClient.lRange("simplelist", 3, 1);

console.log("Command: lRange simplelist 3 1 | Result:", commandResult);

/**
 * When the provided index is out of range, then the command adjusts to the starting or ending index
 *
 * Command: lRange simplelist 5 10000
 * Result:
 *      1) "sixth"
 *      2) "seventh"
 *      3) "eighth"
 */
commandResult = await redisClient.lRange("simplelist", 5, 10_000);

console.log("Command: lRange simplelist 5 10000 | Result:", commandResult);

/**
 * If range is out of range then it is adjusted with the actual index
 *
 * Command: lRange simplelist -99 999
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 *      7) "seventh"
 *      8) "eighth"
 */
commandResult = await redisClient.lRange("simplelist", -99, 999);

console.log("Command: lRange simplelist -99 999 | Result:", commandResult);

/**
 * Try to get items from a list that does not exist
 * We get an empty array
 * Command: lRange wronglist 0 -1
 * Result: (empty array)
 */
commandResult = await redisClient.lRange("wronglist", 0, -1);

console.log("Command: lRange wronglist 0 -1 | Result:", commandResult);

/**
 * Set a string value
 *
 * Command: set keyone "some value for key one"
 * Result: OK
 */
commandResult = await redisClient.set("keyone", "some value for key one");

console.log("Command: set keyone "some value for key one" | Result:" + commandResult);

/**
 * Try to use LRANGE for an element that is not a list
 * We get an error for WRONGTYPE
 *
 * Command: lRange keyone 0 -1
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    commandResult = await redisClient.lRange("keyone", 0, 5);

    console.log("Command: lRange keyone 0 -1 | Result:", commandResult);
} catch (e) {
    console.log("Command: lRange keyone 0 -1 | Error: ", e);
}


process.exit(0);

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lRange simplelist 0 5 | Result: [ 'first item', 'second item', 'third', 'fourth', 'fifth', 'sixth' ]

Command: lRange simplelist 0 -1 | Result: [
  'first item',
  'second item',
  'third',
  'fourth',
  'fifth',
  'sixth',
  'seventh',
  'eighth'
]

Command: lRange simplelist 5 -1 | Result: [ 'sixth', 'seventh', 'eighth' ]

Command: lRange simplelist -5 -1 | Result: [ 'fourth', 'fifth', 'sixth', 'seventh', 'eighth' ]

Command: lRange simplelist 3 1 | Result: []

Command: lRange simplelist 5 10000 | Result: [ 'sixth', 'seventh', 'eighth' ]

Command: lRange simplelist -99 999 | Result: [
  'first item',
  'second item',
  'third',
  'fourth',
  'fifth',
  'sixth',
  'seventh',
  'eighth'
]

Command: lRange wronglist 0 -1 | Result: []

Command: set keyone "some value for key one" | Result:OK
Command: lRange keyone 0 -1 | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use method “lRange” from the package node-redis.
// Redis LRANGE Command example in Java

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

public class Lrange {
    public static void main(String[] args) {
        // Create connection pool
        JedisPool jedisPool = new JedisPool("localhost", 6379);

        try (Jedis jedis = jedisPool.getResource()) {

            /**
             * Create list with 8 items
             *
             * Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
             * Result: (integer) 8
             */
            long listCreateResult = jedis.rpush("simplelist", "first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth");

            System.out.println("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: " + listCreateResult);

            /**
             * Get item from list from start to the 5th index
             *
             * Command: lrange simplelist 0 5
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             */
            List<String> lrangeResult = jedis.lrange("simplelist", 0, 5);

            System.out.println("Command: lrange simplelist 0 5 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Get list items from start to the end(all items)
             *
             * Command: lrange simplelist 0 -1
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             *      7) "seventh"
             *      8) "eighth"
             */
            lrangeResult = jedis.lrange("simplelist", 0, -1);

            System.out.println("Command: lrange simplelist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Get list items from 5th index to the end of list
             *
             * Command: lrange simplelist 5 -1
             * Result:
             *      1) "sixth"
             *      2) "seventh"
             *      3) "eighth"
             */
            lrangeResult = jedis.lrange("simplelist", 5, -1);

            System.out.println("Command: lrange simplelist 5 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Get list items from 5th index(from end) to the last item
             *
             * Command: lrange simplelist -5 -1
             * Result:
             *      1) "fourth"
             *      2) "fifth"
             *      3) "sixth"
             *      4) "seventh"
             *      5) "eighth"
             */
            lrangeResult = jedis.lrange("simplelist", -5, -1);

            System.out.println("Command: lrange simplelist -5 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Try to get list items with starting index larger that end index
             * We get an empty list
             * Command: lrange simplelist 3 1
             * Result: (empty array)
             */
            lrangeResult = jedis.lrange("simplelist", 3, 1);

            System.out.println("Command: lrange simplelist 3 1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * When the provided index is out of range, then the command adjusts to the starting or ending index
             *
             * Command: lrange simplelist 5 10000
             * Result:
             *      1) "sixth"
             *      2) "seventh"
             *      3) "eighth"
             */
            lrangeResult = jedis.lrange("simplelist", 5, 10_000);

            System.out.println("Command: lrange simplelist 5 10000 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * If range is out of range then it is adjusted with the actual index
             *
             * Command: lrange simplelist -99 999
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             *      7) "seventh"
             *      8) "eighth"
             */
            lrangeResult = jedis.lrange("simplelist", -99, 999);

            System.out.println("Command: lrange simplelist -99 999 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Try to get items from a list that does not exist
             * We get an empty array
             * Command: lrange wronglist 0 -1
             * Result: (empty array)
             */
            lrangeResult = jedis.lrange("wronglist", 0, -1);

            System.out.println("Command: lrange wronglist 0 -1 | Result:");

            for (String item : lrangeResult) {
                System.out.println(item);
            }

            /**
             * Set a string value
             *
             * Command: set keyone "some value for key one"
             * Result: OK
             */
            String setResult = jedis.set("keyone", "some value for key one");

            System.out.println("Command: set keyone "some value for key one" | Result:" + setResult);

            /**
             * Try to use LRANGE for an element that is not a list
             * We get an error for WRONGTYPE
             *
             * Command: lrange keyone 0 -1
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                lrangeResult = jedis.lrange("keyone", 0, 5);

                System.out.println("Command: lrange keyone 0 -1 | Result:");

                for (String item : lrangeResult) {
                    System.out.println(item);
                }
            } catch (Exception e) {
                System.out.println("Command: lrange keyone 0 -1 | Error: " + e.getMessage());
            }

        }

        jedisPool.close();
    }
}

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:
first item
second item
third
fourth
fifth
sixth

Command: lrange simplelist 0 -1 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 5 -1 | Result:
sixth
seventh
eighth

Command: lrange simplelist -5 -1 | Result:
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 3 1 | Result:

Command: lrange simplelist 5 10000 | Result:
sixth
seventh
eighth

Command: lrange simplelist -99 999 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange wronglist 0 -1 | Result:

Command: set keyone "some value for key one" | Result:OK

Command: lrange keyone 0 -1 | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “lrange” from Jedis package.
  • Signature of the “getrange” is-
    public List<String> lrange(final String key, final long start, final long stop)
// Redis LRANGE command examples in C#

using StackExchange.Redis;

namespace Lrange
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase rdb = redis.GetDatabase();

            /**
             * Create list with 8 items
             *
             * Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
             * Result: (integer) 8
             */
            long listCreateResult = rdb.ListRightPush("simplelist", new RedisValue[] { "first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"});

            Console.WriteLine("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: " + listCreateResult);

            /**
             * Get item from list from start to the 5th index
             *
             * Command: lrange simplelist 0 5
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             */
            RedisValue[]  lrangeResult = rdb.ListRange("simplelist", 0, 5);
            Console.WriteLine("Command: lrange simplelist 0 5 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Get list items from start to the end(all items)
             *
             * Command: lrange simplelist 0 -1
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             *      7) "seventh"
             *      8) "eighth"
             */
            lrangeResult = rdb.ListRange("simplelist", 0, -1);

            Console.WriteLine("Command: lrange simplelist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Get list items from 5th index to the end of list
             *
             * Command: lrange simplelist 5 -1
             * Result:
             *      1) "sixth"
             *      2) "seventh"
             *      3) "eighth"
             */
            lrangeResult = rdb.ListRange("simplelist", 5, -1);

            Console.WriteLine("Command: lrange simplelist 5 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Get list items from 5th index(from end) to the last item
             *
             * Command: lrange simplelist -5 -1
             * Result:
             *      1) "fourth"
             *      2) "fifth"
             *      3) "sixth"
             *      4) "seventh"
             *      5) "eighth"
             */
            lrangeResult = rdb.ListRange("simplelist", -5, -1);

            Console.WriteLine("Command: lrange simplelist -5 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Try to get list items with starting index larger that end index
             * We get an empty list
             * Command: lrange simplelist 3 1
             * Result: (empty array)
             */
            lrangeResult = rdb.ListRange("simplelist", 3, 1);

            Console.WriteLine("Command: lrange simplelist 3 1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * When the provided index is out of range, then the command adjusts to the starting or ending index
             *
             * Command: lrange simplelist 5 10000
             * Result:
             *      1) "sixth"
             *      2) "seventh"
             *      3) "eighth"
             */
            lrangeResult = rdb.ListRange("simplelist", 5, 10_000);

            Console.WriteLine("Command: lrange simplelist 5 10000 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * If range is out of range then it is adjusted with the actual index
             *
             * Command: lrange simplelist -99 999
             * Result:
             *      1) "first item"
             *      2) "second item"
             *      3) "third"
             *      4) "fourth"
             *      5) "fifth"
             *      6) "sixth"
             *      7) "seventh"
             *      8) "eighth"
             */
            lrangeResult = rdb.ListRange("simplelist", -99, 999);

            Console.WriteLine("Command: lrange simplelist -99 999 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Try to get items from a list that does not exist
             * We get an empty array
             * Command: lrange wronglist 0 -1
             * Result: (empty array)
             */
            lrangeResult = rdb.ListRange("wronglist", 0, -1);

            Console.WriteLine("Command: lrange wronglist 0 -1 | Result:");

            foreach (var item in lrangeResult)
            {
                Console.WriteLine(item);
            }

            /**
             * Set a string value
             *
             * Command: set keyone "some value for key one"
             * Result: OK
             */
            bool setResult = rdb.StringSet("keyone", "some value for key one");

            Console.WriteLine("Command: set keyone "some value for key one" | Result:" + setResult);

            /**
             * Try to use LRANGE for an element that is not a list
             * We get an error for WRONGTYPE
             *
             * Command: lrange keyone 0 -1
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                lrangeResult = rdb.ListRange("keyone", 0, 5);

                Console.WriteLine("Command: lrange keyone 0 -1 | Result:");

                foreach (var item in lrangeResult)
                {
                    Console.WriteLine(item);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: lrange keyone 0 -1 | Error: " + e.Message);
            }
        }
    }
}

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:
first item
second item
third
fourth
fifth
sixth

Command: lrange simplelist 0 -1 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 5 -1 | Result:
sixth
seventh
eighth

Command: lrange simplelist -5 -1 | Result:
fourth
fifth
sixth
seventh
eighth

Command: lrange simplelist 3 1 | Result:

Command: lrange simplelist 5 10000 | Result:
sixth
seventh
eighth

Command: lrange simplelist -99 999 | Result:
first item
second item
third
fourth
fifth
sixth
seventh
eighth

Command: lrange wronglist 0 -1 | Result:

Command: set keyone "some value for key one" | Result:True
Command: lrange keyone 0 -1 | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “ListRange” from StackExchange.Redis.
  • Signature of the method is-
    RedisValue[] ListRange(RedisKey key, long start = 0, long stop = -1, CommandFlags flags = CommandFlags.None)
<?php
// Redis LRANGE command example in PHP

require 'vendor/autoload.php';

// Connect to Redis
$redisClient = new PredisClient([
    'scheme' => 'tcp',
    'host' => 'localhost',
    'port' => 6379,
]);


/**
 * Create list with 8 items
 *
 * Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
 * Result: (integer) 8
 */
$commandResult = $redisClient->rpush("simplelist", ["first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]);

echo "Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: " . $commandResult . "n";

/**
 * Get item from list from start to the 5th index
 *
 * Command: lrange simplelist 0 5
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 */
$commandResult = $redisClient->lrange("simplelist", 0, 5);

echo "Command: lrange simplelist 0 5 | Result:n";
print_r($commandResult);

/**
 * Get list items from start to the end(all items)
 *
 * Command: lrange simplelist 0 -1
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 *      7) "seventh"
 *      8) "eighth"
 */
$commandResult = $redisClient->lrange("simplelist", 0, -1);

echo "Command: lrange simplelist 0 -1 | Result:n";
print_r($commandResult);

/**
 * Get list items from 5th index to the end of list
 *
 * Command: lrange simplelist 5 -1
 * Result:
 *      1) "sixth"
 *      2) "seventh"
 *      3) "eighth"
 */
$commandResult = $redisClient->lrange("simplelist", 5, -1);

echo "Command: lrange simplelist 5 -1 | Result:n";
print_r($commandResult);

/**
 * Get list items from 5th index(from end) to the last item
 *
 * Command: lrange simplelist -5 -1
 * Result:
 *      1) "fourth"
 *      2) "fifth"
 *      3) "sixth"
 *      4) "seventh"
 *      5) "eighth"
 */
$commandResult = $redisClient->lrange("simplelist", -5, -1);

echo "Command: lrange simplelist -5 -1 | Result:n";
print_r($commandResult);

/**
 * Try to get list items with starting index larger that end index
 * We get an empty list
 * Command: lrange simplelist 3 1
 * Result: (empty array)
 */
$commandResult = $redisClient->lrange("simplelist", 3, 1);

echo "Command: lrange simplelist 3 1 | Result:n";
print_r($commandResult);

/**
 * When the provided index is out of range, then the command adjusts to the starting or ending index
 *
 * Command: lrange simplelist 5 10000
 * Result:
 *      1) "sixth"
 *      2) "seventh"
 *      3) "eighth"
 */
$commandResult = $redisClient->lrange("simplelist", 5, 10_000);

echo "Command: lrange simplelist 5 10000 | Result:n";
print_r($commandResult);

/**
 * If range is out of range then it is adjusted with the actual index
 *
 * Command: lrange simplelist -99 999
 * Result:
 *      1) "first item"
 *      2) "second item"
 *      3) "third"
 *      4) "fourth"
 *      5) "fifth"
 *      6) "sixth"
 *      7) "seventh"
 *      8) "eighth"
 */
$commandResult = $redisClient->lrange("simplelist", -99, 999);

echo "Command: lrange simplelist -99 999 | Result:n";
print_r($commandResult);

/**
 * Try to get items from a list that does not exist
 * We get an empty array
 * Command: lrange wronglist 0 -1
 * Result: (empty array)
 */
$commandResult = $redisClient->lrange("wronglist", 0, -1);

echo "Command: lrange wronglist 0 -1 | Result:n";
print_r($commandResult);

/**
 * Set a string value
 *
 * Command: set keyone "some value for key one"
 * Result: OK
 */
$commandResult = $redisClient->set("keyone", "some value for key one");

echo "Command: set keyone "some value for key one" | Result:" . $commandResult . "n";

/**
 * Try to use LRANGE for an element that is not a list
 * We get an error for WRONGTYPE
 *
 * Command: lrange keyone 0 -1
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->lrange("keyone", 0, 5);

    echo "Command: lrange keyone 0 -1 | Result:n";
    print_r($commandResult);
} catch (Exception $e) {
    echo "Command: lrange keyone 0 -1 | Error: " . $e->getMessage() . "n";
}

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:
Array
(
    [0] => first item
    [1] => second item
    [2] => third
    [3] => fourth
    [4] => fifth
    [5] => sixth
)

Command: lrange simplelist 0 -1 | Result:
Array
(
    [0] => first item
    [1] => second item
    [2] => third
    [3] => fourth
    [4] => fifth
    [5] => sixth
    [6] => seventh
    [7] => eighth
)

Command: lrange simplelist 5 -1 | Result:
Array
(
    [0] => sixth
    [1] => seventh
    [2] => eighth
)

Command: lrange simplelist -5 -1 | Result:
Array
(
    [0] => fourth
    [1] => fifth
    [2] => sixth
    [3] => seventh
    [4] => eighth
)

Command: lrange simplelist 3 1 | Result:
Array
(
)

Command: lrange simplelist 5 10000 | Result:
Array
(
    [0] => sixth
    [1] => seventh
    [2] => eighth
)

Command: lrange simplelist -99 999 | Result:
Array
(
    [0] => first item
    [1] => second item
    [2] => third
    [3] => fourth
    [4] => fifth
    [5] => sixth
    [6] => seventh
    [7] => eighth
)

Command: lrange wronglist 0 -1 | Result:
Array
(
)

Command: set keyone "some value for key one" | Result:OK
Command: lrange keyone 0 -1 | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “lrange” of predis.
  • Signature of the method is-
    lrange(string $key, int $start, int $stop): string[]
# Redis LRANGE command example in Python

import redis
import time

# Create Redis client
redisClient = redis.Redis(host='localhost', port=6379,
                          username='default', password='',
                          decode_responses=True)


# Create list with 8 items
# Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
# Result: (integer) 8
commandResult = redisClient.rpush("simplelist", "first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth")

print("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: {}".format(commandResult))

# Get item from list from start to the 5th index
# Command: lrange simplelist 0 5
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
commandResult = redisClient.lrange("simplelist", 0, 5)

print("Command: lrange simplelist 0 5 | Result:{}".format(commandResult))

# Get list items from start to the end(all items)
# Command: lrange simplelist 0 -1
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
#      7) "seventh"
#      8) "eighth"
commandResult = redisClient.lrange("simplelist", 0, -1)

print("Command: lrange simplelist 0 -1 | Result:{}".format(commandResult))

# Get list items from 5th index to the end of list
# Command: lrange simplelist 5 -1
# Result:
#      1) "sixth"
#      2) "seventh"
#      3) "eighth"
commandResult = redisClient.lrange("simplelist", 5, -1)

print("Command: lrange simplelist 5 -1 | Result:{}".format(commandResult))

# Get list items from 5th index(from end) to the last item
# Command: lrange simplelist -5 -1
# Result:
#      1) "fourth"
#      2) "fifth"
#      3) "sixth"
#      4) "seventh"
#      5) "eighth"
commandResult = redisClient.lrange("simplelist", -5, -1)

print("Command: lrange simplelist -5 -1 | Result:{}".format(commandResult))

# Try to get list items with starting index larger that end index
# We get an empty list
# Command: lrange simplelist 3 1
# Result: (empty array)
commandResult = redisClient.lrange("simplelist", 3, 1)

print("Command: lrange simplelist 3 1 | Result:{}".format(commandResult))

# When the provided index is out of range, then the command adjusts to the starting or ending index
# Command: lrange simplelist 5 10000
# Result:
#      1) "sixth"
#      2) "seventh"
#      3) "eighth"
commandResult = redisClient.lrange("simplelist", 5, 10_000)

print("Command: lrange simplelist 5 10000 | Result:{}".format(commandResult))

# If range is out of range then it is adjusted with the actual index
# Command: lrange simplelist -99 999
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
#      7) "seventh"
#      8) "eighth"
commandResult = redisClient.lrange("simplelist", -99, 999)

print("Command: lrange simplelist -99 999 | Result:{}".format(commandResult))

# Try to get items from a list that does not exist
# We get an empty array
# Command: lrange wronglist 0 -1
# Result: (empty array)
commandResult = redisClient.lrange("wronglist", 0, -1)

print("Command: lrange wronglist 0 -1 | Result:{}".format(commandResult))


# Set a string value
# Command: set keyone "some value for key one"
# Result: OK
commandResult = redisClient.set("keyone", "some value for key one")

print("Command: set keyone "some value for key one" | Result:{}".format(commandResult))

# Try to use LRANGE for an element that is not a list
# We get an error for WRONGTYPE
# Command: lrange keyone 0 -1
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.lrange("keyone", 0, 5)

    print("Command: lrange keyone 0 -1 | Result:{}".format(commandResult))

except Exception as error:
    print("Command: lrange keyone 0 -1 | Error: ", error)

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:['first item', 'second item', 'third', 'fourth', 'fifth', 'sixth']

Command: lrange simplelist 0 -1 | Result:['first item', 'second item', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth']    

Command: lrange simplelist 5 -1 | Result:['sixth', 'seventh', 'eighth']

Command: lrange simplelist -5 -1 | Result:['fourth', 'fifth', 'sixth', 'seventh', 'eighth']

Command: lrange simplelist 3 1 | Result:[]

Command: lrange simplelist 5 10000 | Result:['sixth', 'seventh', 'eighth']

Command: lrange simplelist -99 999 | Result:['first item', 'second item', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth'] 

Command: lrange wronglist 0 -1 | Result:[]

Command: set keyone "some value for key one" | Result:True
Command: lrange keyone 0 -1 | Error:  WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “lrange” from redis-py.
  • Signature of the method is –
    def lrange(self, name: str, start: int, end: int) -> Union[Awaitable[list], list]
# Redis LRANGE command example in Ruby

require 'redis'

redis = Redis.new(host: "localhost", port: 6379)

# Create list with 8 items
# Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth
# Result: (integer) 8
commandResult = redis.rpush("simplelist", ["first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"])

print("Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: ", commandResult, "n")

# Get item from list from start to the 5th index
# Command: lrange simplelist 0 5
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
commandResult = redis.lrange("simplelist", 0, 5)

print("Command: lrange simplelist 0 5 | Result:", commandResult, "n")

# Get list items from start to the end(all items)
# Command: lrange simplelist 0 -1
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
#      7) "seventh"
#      8) "eighth"
commandResult = redis.lrange("simplelist", 0, -1)

print("Command: lrange simplelist 0 -1 | Result:", commandResult, "n")

# Get list items from 5th index to the end of list
# Command: lrange simplelist 5 -1
# Result:
#      1) "sixth"
#      2) "seventh"
#      3) "eighth"
commandResult = redis.lrange("simplelist", 5, -1)

print("Command: lrange simplelist 5 -1 | Result:", commandResult, "n")

# Get list items from 5th index(from end) to the last item
# Command: lrange simplelist -5 -1
# Result:
#      1) "fourth"
#      2) "fifth"
#      3) "sixth"
#      4) "seventh"
#      5) "eighth"
commandResult = redis.lrange("simplelist", -5, -1)

print("Command: lrange simplelist -5 -1 | Result:", commandResult, "n")

# Try to get list items with starting index larger that end index
# We get an empty list
# Command: lrange simplelist 3 1
# Result: (empty array)
commandResult = redis.lrange("simplelist", 3, 1)

print("Command: lrange simplelist 3 1 | Result:", commandResult, "n")

# When the provided index is out of range, then the command adjusts to the starting or ending index
# Command: lrange simplelist 5 10000
# Result:
#      1) "sixth"
#      2) "seventh"
#      3) "eighth"
commandResult = redis.lrange("simplelist", 5, 10_000)

print("Command: lrange simplelist 5 10000 | Result:", commandResult, "n")

# If range is out of range then it is adjusted with the actual index
# Command: lrange simplelist -99 999
# Result:
#      1) "first item"
#      2) "second item"
#      3) "third"
#      4) "fourth"
#      5) "fifth"
#      6) "sixth"
#      7) "seventh"
#      8) "eighth"
commandResult = redis.lrange("simplelist", -99, 999)

print("Command: lrange simplelist -99 999 | Result:", commandResult, "n")

# Try to get items from a list that does not exist
# We get an empty array
# Command: lrange wronglist 0 -1
# Result: (empty array)
commandResult = redis.lrange("wronglist", 0, -1)

print("Command: lrange wronglist 0 -1 | Result:", commandResult, "n")


# Set a string value
# Command: set keyone "some value for key one"
# Result: OK
commandResult = redis.set("keyone", "some value for key one")

print("Command: set keyone "some value for key one" | Result:", commandResult, "n")

# Try to use LRANGE for an element that is not a list
# We get an error for WRONGTYPE
# Command: lrange keyone 0 -1
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.lrange("keyone", 0, 5)

    print("Command: lrange keyone 0 -1 | Result:", commandResult, "n")
rescue => e
    print("Command: lrange keyone 0 -1 | Error: ", e)
end

Output:

Command: rpush simplelist "first item" "second item" "third" fourth fifth sixth "seventh" eighth | Result: 8

Command: lrange simplelist 0 5 | Result:["first item", "second item", "third", "fourth", "fifth", "sixth"]

Command: lrange simplelist 0 -1 | Result:["first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]

Command: lrange simplelist 5 -1 | Result:["sixth", "seventh", "eighth"]

Command: lrange simplelist -5 -1 | Result:["fourth", "fifth", "sixth", "seventh", "eighth"]

Command: lrange simplelist 3 1 | Result:[]

Command: lrange simplelist 5 10000 | Result:["sixth", "seventh", "eighth"]

Command: lrange simplelist -99 999 | Result:["first item", "second item", "third", "fourth", "fifth", "sixth", "seventh", "eighth"]

Command: lrange wronglist 0 -1 | Result:[]

Command: set keyone "some value for key one" | Result:OK
Command: lrange keyone 0 -1 | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “lrange” from the redis-rb.
  • Signature of the “lrange” method is-
    # @param [String] key
    # @param [Integer] start start index
    # @param [Integer] stop stop index
    # @return [Array<String>]

    def lrange(key, start, stop)

Source Code

Use the following links to get the source code used in this article-

Related Commands

CommandDetails
LPUSH Command Details
RPUSH Command Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.