In Redis, the LSET
command allows us to set a list element to a different value, based on its index.
Syntax
The syntax goes like this:
LSET key index element
The way it works is that the element at index
is set to the value specified at element
.
Example
Suppose we create a list like this:
RPUSH animals Cat Dog Ant Cow
Result:
(integer) 4
Let’s take a look at the list:
LRANGE animals 0 -1
Result:
1) "Cat" 2) "Dog" 3) "Ant" 4) "Cow"
Let’s now use the LSET
command to set an element’s value, based on its index:
LSET animals 2 "Horse"
Result:
OK
A simple string reply of OK
indicates that the operation was successful.
Now when we check the list again, we can see that it has been updated with the new value:
LRANGE animals 0 -1
Result:
1) "Cat" 2) "Dog" 3) "Horse" 4) "Cow"
Note that lists are zero based, and so when we specified an index of 2
, it actually updated the third value in the list.
Negative Indexes
Specifying a negative index designates elements starting from the tail of the list:
LSET animals -2 "Buffalo"
Result:
OK
Now let’s take another look at the list:
LRANGE animals 0 -1
Result:
1) "Cat" 2) "Dog" 3) "Buffalo" 4) "Cow"
In this case we updated the same element, but we did it by specifying its index counting backwards from the tail of the list.
Out of Range Indexes
Specifying an out of range index results in an error:
LSET animals 20 "Horse"
Result:
(error) ERR index out of range