How to Use LSET Command in Redis to Update List Elements
The
LSET command in Redis updates the element at a specific index in a list stored at a key. Use LSET key index value to replace the element at index with value. The index can be positive (from start) or negative (from end).Syntax
The LSET command updates an element in a Redis list at a given index.
- key: The name of the list.
- index: Position of the element to update (0-based, negative counts from the end).
- value: New value to set at the specified index.
If the index is out of range, Redis returns an error.
redis
LSET key index value
Example
This example shows how to update the second element (index 1) in a list called fruits from "banana" to "blueberry".
redis
127.0.0.1:6379> RPUSH fruits apple banana cherry (integer) 3 127.0.0.1:6379> LRANGE fruits 0 -1 1) "apple" 2) "banana" 3) "cherry" 127.0.0.1:6379> LSET fruits 1 blueberry OK 127.0.0.1:6379> LRANGE fruits 0 -1 1) "apple" 2) "blueberry" 3) "cherry"
Output
1) "apple"
2) "banana"
3) "cherry"
OK
1) "apple"
2) "blueberry"
3) "cherry"
Common Pitfalls
Common mistakes when using LSET include:
- Using an index that is out of range, which causes an error.
- Trying to use
LSETon a key that does not hold a list. - Confusing zero-based indexing with one-based indexing.
Always check the list length with LLEN before using LSET to avoid errors.
redis
127.0.0.1:6379> LSET fruits 5 mango (error) ERR index out of range 127.0.0.1:6379> SET notalist value OK 127.0.0.1:6379> LSET notalist 0 something (error) WRONGTYPE Operation against a key holding the wrong kind of value
Output
(error) ERR index out of range
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Quick Reference
| Command | Description |
|---|---|
| LSET key index value | Set list element at index to value |
| LLEN key | Get length of the list |
| LRANGE key start stop | Get elements in a range |
| RPUSH key value | Add element to the end of the list |
Key Takeaways
Use LSET to update an element at a specific index in a Redis list.
Indexes are zero-based; negative indexes count from the end of the list.
LSET returns an error if the index is out of range or the key is not a list.
Check list length with LLEN before using LSET to avoid errors.
LSET modifies the list in place without changing its length.