How to Use LLEN Command in Redis to Get List Length
Use the
LLEN command in Redis to get the number of elements in a list stored at a given key. The command syntax is LLEN key, which returns an integer representing the list length.Syntax
The LLEN command syntax is simple:
LLEN key: Returns the length of the list stored atkey.- If the key does not exist, it returns 0.
- If the key exists but is not a list, it returns an error.
redis
LLEN mylist
Example
This example shows how to create a list, add elements, and then use LLEN to get its length.
redis
127.0.0.1:6379> LPUSH mylist "apple" (integer) 1 127.0.0.1:6379> LPUSH mylist "banana" (integer) 2 127.0.0.1:6379> LPUSH mylist "cherry" (integer) 3 127.0.0.1:6379> LLEN mylist (integer) 3
Output
(integer) 3
Common Pitfalls
Common mistakes when using LLEN include:
- Using
LLENon a key that is not a list, which causes an error. - Expecting
LLENto returnnullfor non-existing keys; it returns 0 instead. - Confusing
LLENwith commands that return list elements.
redis
127.0.0.1:6379> SET mykey "notalist" OK 127.0.0.1:6379> LLEN mykey (error) WRONGTYPE Operation against a key holding the wrong kind of value -- Correct usage -- 127.0.0.1:6379> LLEN nonexistingkey (integer) 0
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
(integer) 0
Quick Reference
| Command | Description | Returns |
|---|---|---|
| LLEN key | Get length of list at key | Integer length or 0 if key missing |
| LPUSH key value | Add value to front of list | New list length |
| LRANGE key start stop | Get elements from list | List of elements |
Key Takeaways
Use LLEN to get the number of elements in a Redis list by specifying its key.
LLEN returns 0 if the list key does not exist, not an error or null.
Using LLEN on a non-list key causes a type error.
LPUSH can add elements to a list before checking its length with LLEN.
LLEN only returns the count, not the list elements themselves.