0
0
RedisHow-ToBeginner · 3 min read

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 at key.
  • 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 LLEN on a key that is not a list, which causes an error.
  • Expecting LLEN to return null for non-existing keys; it returns 0 instead.
  • Confusing LLEN with 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

CommandDescriptionReturns
LLEN keyGet length of list at keyInteger length or 0 if key missing
LPUSH key valueAdd value to front of listNew list length
LRANGE key start stopGet elements from listList 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.