In Redis, Lists store an ordered sequence of strings.
We can use the following commands to add elements from lists in Redis:
LPUSH
commandThe LPUSH
command is used to add elements at the beginning of the list.
Before carrying out the push operations, an empty list is generated if it does not already exist. An error is produced if the key contains a value that is not a list.
The syntax is as follows:
LPUSH key value1 ... valueN
key
: This is the name under which the list is registered.value[X]
: This is the value to be added to the list.RPUSH
commandThe RPUSH
command is used to append the elements to the list.
Before carrying out the push operations, an empty list is generated if it does not already exist. An error is produced if the key contains a value that is not a list.
The syntax is as follows:
RPUSH key value1 ... valueN
key
: This is the name under which the list is registered.value[X]
: These are the values to be added to the list.We can use the following commands to remove elements from lists in Redis:
LPOP
commandThe LPOP
command is used to remove elements from the beginning of the list.
By default, the command removes a single element from the beginning of the list. With the help of the count
option, we can specify the number of elements to be removed.
The syntax is as follows:
LPOP key [count]
key
: This is the name under which the list is registered.count
: This is the number of elements to be removed.RPOP
commandThe LPOP
command is used to remove elements from the end of the list.
By default, the command removes a single element from the end of the list. We can specify the number of elements to be removed With the help of the count
option.
The syntax is as follows:
RPOP key [count]
key
: This is the name under which the list is registered.count
: This is the number of elements to be removed.Some of the other common commands are as follows:
LLEN
commandThe LLEN
command is used to return the length of the list.
The syntax is as follows:
LLEN key
key
: This is the name under which the list is registered.LPUSH lst hi hello educative
LLEN lst
LPOP lst
RPUSH lst new-hi new-hello
RPOP lst
We can run the above commands in the following terminal: