How to Use LINDEX in Redis: Syntax and Examples
Use the
LINDEX command in Redis to get the element at a specific index from a list stored at a key. The syntax is LINDEX key index, where index is zero-based and can be negative to count from the end.Syntax
The LINDEX command retrieves an element from a list by its index.
- key: The name of the list in Redis.
- index: The position of the element you want, starting at 0 for the first element. Negative numbers count from the end (-1 is the last element).
redis
LINDEX key index
Example
This example shows how to add elements to a list and then get an element by its index using LINDEX.
redis
127.0.0.1:6379> RPUSH fruits "apple" "banana" "cherry" (integer) 3 127.0.0.1:6379> LINDEX fruits 1 "banana" 127.0.0.1:6379> LINDEX fruits -1 "cherry"
Output
"banana"
"cherry"
Common Pitfalls
Common mistakes when using LINDEX include:
- Using an index out of range returns
(nil)instead of an error. - Forgetting that indexes start at 0, so
LINDEX key 0gets the first element. - Using
LINDEXon a key that is not a list returns an error.
redis
127.0.0.1:6379> LINDEX fruits 10 (nil) 127.0.0.1:6379> SET notalist "hello" OK 127.0.0.1:6379> LINDEX notalist 0 (error) WRONGTYPE Operation against a key holding the wrong kind of value
Output
(nil)
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Quick Reference
| Command | Description |
|---|---|
| LINDEX key index | Get element at index from list key |
| RPUSH key value [value ...] | Add elements to the end of the list |
| LLEN key | Get the length of the list |
Key Takeaways
LINDEX gets an element from a Redis list by zero-based index.
Negative indexes count from the end of the list (-1 is last).
Out-of-range indexes return null, not an error.
LINDEX only works on list keys; other types cause errors.
Use RPUSH to add elements before using LINDEX to retrieve them.