Redis Command: LLEN

Summary

Command NameLLEN
UsageGet list length
Group list
ACL Category@read
@list
@fast
Time ComplexityO(1)
FlagREADONLY
FAST
Arity2

Signature

LLEN <key>

Usage

Get the length of a list. We get zero as a result for a non-existing list and an exception is thrown for a wrong data type.

Arguments

ParameterDescriptionNameType
<key>Key name of the listkeykey

Return Value

Return valueCase for the return valueType
Length of listIf the operation was successful, and the list existsinteger
Zero(0)If the key does not existsinteger
errorIf the data type of key is not a listerror

Notes

  • If key is not of type list, the following error message is returned-
    (error) WRONGTYPE Operation against a key holding the wrong kind of value

Examples

Here are a few examples of the LLEN command usage-

# Redis LLEN command examples

# Create list and push element. We are pushing 5 elements to the list
127.0.0.1:6379> rpush bigboxlist one two three four five
(integer) 5

# Check length of the list
127.0.0.1:6379> llen bigboxlist
(integer) 5

# Use LLEN for an non existing key
# It returns Zero(0)
127.0.0.1:6379> llen nonexistingkey
(integer) 0

# Set a string key/value
127.0.0.1:6379> set somestrkey "my string value here for test"
OK

# Try to use LLEN command for string type key
# It returns error which indicates, the type of key is wrong
127.0.0.1:6379> llen somestrkey
(error) WRONGTYPE Operation against a key holding the wrong kind of value

Code Implementations

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

// Redis LLEN 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 and push element. We are pushing 5 elements to the list
	// Command: rpush bigboxlist one two three four five
	// Result: (integer) 5
	pushResult, err := rdb.RPush(ctx, "bigboxlist", "one", "two", "three", "four", "five").Result()

	if err != nil {
		fmt.Println("Command: rpush bigboxlist one two three four five | Error: " + err.Error())
	}

	fmt.Printf("Command: rpush bigboxlist one two three four five | Result: %vn", pushResult)

	// Check length of the list
	// Command: llen bigboxlist
	// Result: (integer) 5
	listLength, err := rdb.LLen(ctx, "bigboxlist").Result()

	if err != nil {
		fmt.Println("Command: llen bigboxlist | Error: " + err.Error())
	}

	fmt.Printf("Command: llen bigboxlist | Result: %vn", listLength)

	// Use LLEN for an non existing key
	// It returns Zero(0)
	// Command: llen nonexistingkey
	// Result: (integer) 0
	listLength, err = rdb.LLen(ctx, "nonexistingkey").Result()

	if err != nil {
		fmt.Println("Command: llen nonexistingkey | Error: " + err.Error())
	}

	fmt.Printf("Command: llen nonexistingkey | Result: %vn", listLength)

	// Set a string key/value
	// Command: set somestrkey "my string value here for test"
	// Result: OK
	setResult, err := rdb.Set(ctx, "somestrkey", "my string value here for test", 0).Result()

	if err != nil {
		fmt.Println("Command: set somestrkey "my string value here for test" | Error: " + err.Error())
	}

	fmt.Println("Command: set somestrkey "my string value here for test" | Result: " + setResult)

	// Try to use LLEN command for string type key
	// It returns error which indicates, the type of key is wrong
	// Command: llen somestrkey
	// Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
	listLength, err = rdb.LLen(ctx, "somestrkey").Result()

	if err != nil {
		fmt.Println("Command: llen somestrkey | Error: " + err.Error())
	}

	fmt.Printf("Command: llen somestrkey | Result: %vn", listLength)

}

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: OK
Command: llen somestrkey | Error: WRONGTYPE Operation against a key holding the wrong kind of value
Command: llen somestrkey | Result: 0

Notes

  • Use “LIndex” method from redis-go module.
  • Signature of the method is-
    LIndex(ctx context.Context, key string, index int64) *StringCmd
// Redis LLEN command example in JavaScript(NodeJS)

import { createClient } from "redis";

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

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

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

/**
 * Create list and push element. We are pushing 5 elements to the list
 *
 * Command: rpush bigboxlist one two three four five
 * Result: (integer) 5
 */
let commandResult = await redisClient.rPush("bigboxlist", [
  "one",
  "two",
  "three",
  "four",
  "five"
]);

console.log(
  "Command: rpush bigboxlist one two three four five | Result: " + commandResult
);

/**
 * Check length of the list
 *
 * Command: llen bigboxlist
 * Result: (integer) 5
 */
commandResult = await redisClient.lLen("bigboxlist");

console.log("Command: llen bigboxlist | Result: " + commandResult);

/**
 * Use LLEN for an non existing key
 * It returns Zero(0)
 *
 * Command: llen nonexistingkey
 * Result: (integer) 0
 */
commandResult = await redisClient.lLen("nonexistingkey");

console.log("Command: llen nonexistingkey | Result: " + commandResult);

/**
 * Set a string key/value
 *
 * Command: set somestrkey "my string value here for test"
 * Result: OK
 */
commandResult = await redisClient.set("somestrkey", "my string value here for test");

console.log(
  'Command: set somestrkey "my string value here for test" | Result: ' +
    commandResult
);

/**
 * Try to use LLEN command for string type key
 * It returns error which indicates, the type of key is wrong
 *
 * Command: llen somestrkey
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
  commandResult = await redisClient.lLen("somestrkey");

  console.log("Command: llen somestrkey | Result: " + commandResult);
} catch (e) {
  console.log("Command: llen somestrkey | Error: ", e);
}

process.exit(0);

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: OK
Command: llen somestrkey | Error:  [ErrorReply: WRONGTYPE Operation against a key holding the wrong kind of value]

Notes

  • Use the function “lLen” from the package node-redis.
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class Llen {

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

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

            /**
             * Create list and push element. We are pushing 5 elements to the list
             *
             * Command: rpush bigboxlist one two three four five
             * Result: (integer) 5
             */
            long pushResult = jedis.rpush("bigboxlist", "one", "two", "three", "four", "five");

            System.out.println("Command: rpush bigboxlist one two three four five | Result: " + pushResult);

            /**
             * Check length of the list
             *
             * Command: llen bigboxlist
             * Result: (integer) 5
             */
            long listLength = jedis.llen("bigboxlist");

            System.out.println("Command: llen bigboxlist | Result: " + listLength);

            /**
             * Use LLEN for an non existing key
             * It returns Zero(0)
             *
             * Command: llen nonexistingkey
             * Result: (integer) 0
             */
            listLength = jedis.llen("nonexistingkey");

            System.out.println("Command: llen nonexistingkey | Result: " + listLength);

            /**
             * Set a string key/value
             *
             * Command: set somestrkey "my string value here for test"
             * Result: OK
             */
            String setResult = jedis.set("somestrkey", "my string value here for test");

            System.out.println("Command: set somestrkey "my string value here for test" | Result: " + setResult);

            /**
             * Try to use LLEN command for string type key
             * It returns error which indicates, the type of key is wrong
             *
             * Command: llen somestrkey
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try {
                listLength = jedis.llen("somestrkey");

                System.out.println("Command: llen somestrkey | Result: " + listLength);
            } catch (Exception e) {
                System.out.println("Command: llen somestrkey | Error: " + e.getMessage());
            }
        }

        jedisPool.close();
    }
}

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: OK

Command: llen somestrkey | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “llen” from Jedis package.
  • Signature of the method is-
    public long llen(final String key)
// Redis LMOVE command examples in C#

using StackExchange.Redis;

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

            /**
             * Create list and push element. We are pushing 5 elements to the list
             *
             * Command: rpush bigboxlist one two three four five
             * Result: (integer) 5
             */
            long pushResult = rdb.ListRightPush("bigboxlist", new RedisValue[] { "one", "two", "three", "four", "five" });

            Console.WriteLine("Command: rpush bigboxlist one two three four five | Result: " + pushResult);

            /**
             * Check length of the list
             *
             * Command: llen bigboxlist
             * Result: (integer) 5
             */
            long listLength = rdb.ListLength("bigboxlist");

            Console.WriteLine("Command: llen bigboxlist | Result: " + listLength);

            /**
             * Use LLEN for an non existing key
             * It returns Zero(0)
             *
             * Command: llen nonexistingkey
             * Result: (integer) 0
             */
            listLength = rdb.ListLength("nonexistingkey");

            Console.WriteLine("Command: llen nonexistingkey | Result: " + listLength);

            /**
             * Set a string key/value
             *
             * Command: set somestrkey "my string value here for test"
             * Result: OK
             */
            bool setResult = rdb.StringSet("somestrkey", "my string value here for test");

            Console.WriteLine("Command: set somestrkey "my string value here for test" | Result: " + setResult);

            /**
             * Try to use LLEN command for string type key
             * It returns error which indicates, the type of key is wrong
             *
             * Command: llen somestrkey
             * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
             */
            try
            {
                listLength = rdb.ListLength("somestrkey");

                Console.WriteLine("Command: llen somestrkey | Result: " + listLength);
            }
            catch (Exception e)
            {
                Console.WriteLine("Command: llen somestrkey | Error: " + e.Message);
            }
        }
    }
}

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: True
Command: llen somestrkey | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “ListLength” from StackExchange.Redis.
  • Signature of the method is-
    long ListLength(RedisKey key, CommandFlags flags = CommandFlags.None)
<?php
// Redis llen command example in PHP

require 'vendor/autoload.php';

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


/**
 * Create list and push element. We are pushing 5 elements to the list
 *
 * Command: rpush bigboxlist one two three four five
 * Result: (integer) 5
 */
$commandResult = $redisClient->rpush("bigboxlist", [
    "one",
    "two",
    "three",
    "four",
    "five"
]);

echo "Command: rpush bigboxlist one two three four five | Result: " . $commandResult . "n";

/**
 * Check length of the list
 *
 * Command: llen bigboxlist
 * Result: (integer) 5
 */
$commandResult = $redisClient->llen("bigboxlist");

echo "Command: llen bigboxlist | Result: " . $commandResult . "n";

/**
 * Use LLEN for an non existing key
 * It returns Zero(0)
 *
 * Command: llen nonexistingkey
 * Result: (integer) 0
 */
$commandResult = $redisClient->llen("nonexistingkey");

echo "Command: llen nonexistingkey | Result: " . $commandResult . "n";

/**
 * Set a string key/value
 *
 * Command: set somestrkey "my string value here for test"
 * Result: OK
 */
$commandResult = $redisClient->set("somestrkey", "my string value here for test");

echo "Command: set somestrkey "my string value here for test" | Result: " . $commandResult . "n";

/**
 * Try to use LLEN command for string type key
 * It returns error which indicates, the type of key is wrong
 *
 * Command: llen somestrkey
 * Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
 */
try {
    $commandResult = $redisClient->llen("somestrkey");

    echo "Command: llen somestrkey | Result: " . $commandResult . "n";
} catch (Exception $e) {
    echo "Command: llen somestrkey | Error: " . $e->getMessage() . "n";
}

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: OK
Command: llen somestrkey | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use the method “llen” of predis.
  • Signature of the method is-
    llen(string $key): int
# Redis LLEN 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 and push element. We are pushing 5 elements to the list
# Command: rpush bigboxlist one two three four five
# Result: (integer) 5
commandResult = redisClient.rpush(
    "bigboxlist",
    "one",
    "two",
    "three",
    "four",
    "five"
)

print("Command: rpush bigboxlist one two three four five | Result: {}".format(commandResult))

# Check length of the list
# Command: llen bigboxlist
# Result: (integer) 5
commandResult = redisClient.llen("bigboxlist")

print("Command: llen bigboxlist | Result: {}".format(commandResult))

# Use LLEN for an non existing key
# It returns Zero(0)
# Command: llen nonexistingkey
# Result: (integer) 0
commandResult = redisClient.llen("nonexistingkey")

print("Command: llen nonexistingkey | Result: {}".format(commandResult))

# Set a string key/value
# Command: set somestrkey "my string value here for test"
# Result: OK
commandResult = redisClient.set("somestrkey", "my string value here for test")

print("Command: set somestrkey "my string value here for test" | Result: {}".format(commandResult))

# Try to use LLEN command for string type key
# It returns error which indicates, the type of key is wrong
# Command: llen somestrkey
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
try:
    commandResult = redisClient.llen("somestrkey");

    print("Command: llen somestrkey | Result: {}".format(commandResult))
except Exception as error:
    print("Command: llen somestrkey | Error: ", error)

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: True
Command: llen somestrkey | Error:  WRONGTYPE Operation against a key holding the wrong kind of value

Notes

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

require 'redis'

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


# Create list and push element. We are pushing 5 elements to the list
# Command: rpush bigboxlist one two three four five
# Result: (integer) 5
commandResult = redis.rpush("bigboxlist", [
    "one",
    "two",
    "three",
    "four",
    "five"
])

print("Command: rpush bigboxlist one two three four five | Result: ", commandResult, "n")

# Check length of the list
# Command: llen bigboxlist
# Result: (integer) 5
commandResult = redis.llen("bigboxlist")

print("Command: llen bigboxlist | Result: ", commandResult, "n")

# Use LLEN for an non existing key
# It returns Zero(0)
# Command: llen nonexistingkey
# Result: (integer) 0
commandResult = redis.llen("nonexistingkey")

print("Command: llen nonexistingkey | Result: ", commandResult, "n")

# Set a string key/value
# Command: set somestrkey "my string value here for test"
# Result: OK
commandResult = redis.set("somestrkey", "my string value here for test")

print("Command: set somestrkey "my string value here for test" | Result: ", commandResult, "n")

# Try to use LLEN command for string type key
# It returns error which indicates, the type of key is wrong
# Command: llen somestrkey
# Result: (error) WRONGTYPE Operation against a key holding the wrong kind of value
begin
    commandResult = redis.llen("somestrkey");

    print("Command: llen somestrkey | Result: ", commandResult, "n")
rescue => e
    print("Command: llen somestrkey | Error: ", e, "n")
end

Output:

Command: rpush bigboxlist one two three four five | Result: 5

Command: llen bigboxlist | Result: 5

Command: llen nonexistingkey | Result: 0

Command: set somestrkey "my string value here for test" | Result: OK
Command: llen somestrkey | Error: WRONGTYPE Operation against a key holding the wrong kind of value

Notes

  • Use method “llen” from the redis-rb.
  • Signature of the method is-

    # @param [String] key
    # @return [Integer]

    def llen(key)

Source Code

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

Related Commands

CommandDetails
LPUSH Command Details
RPUSH Command Details
LRANGE Command Details

Leave a Comment


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