How to remove & return last element of a list – Redis RPOP | BRPOP

2 months ago Lalit Bhagtani 0

In this tutorial, we will learn about how to remove and return the last element of the list value stored at a key in redis datastore. For this, we will use redis RPOP and BRPOP commands.

RPOP Command

This command is used to remove and return the last element of the list value stored at the specified key. Nil is returned, if a key does not exist and an error is returned, if the key exists but value stored at the key is not of list datatype. The syntax of the Redis RPOP command is as follows:-

Syntax :-

redis host:post> RPOP <keyname>

Output :-

- (string) reply, representing last element of the list.
- (nil), if key does not exists.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis RPOP

BRPOP Command

This command is a blocking version of RPOP command because it blocks the operation when there are no elements to pop from any of the specified lists. In other words, it blocks the operation when all specified lists are empty or all specified keys do not exist.

It removes and returns the last element of a non-empty list value, with the specified keys being checked from left to right. So for example, if command BRPOP list1 list2 list3 0 is executed, where key list1 does not exist ( consider as an empty list ), list2 is an empty list and list3 contains three elements, then it removes and returns the last element of list value stored at list3 as it is the first non empty list, when checking from list1 to list3.

If either the specified key does not exist or specified key’s list value is empty, BRPOP blocks the operation until another client executes a command like LPUSH, RPUSH, and LINSERT to insert an element in one of the specified keys. Once a new element is present on one of the list values, the client returns with the name of the key unblocking it and the popped value.

When BRPOP causes a client to block and a non-zero timeout is specified, the client will unblock returning nil value when the specified timeout has expired without an insert operation against at least one of the specified keys.

A timeout argument is an integer value representing a maximum number of seconds to block. A timeout of 0 seconds can be used to block indefinitely.

The syntax of Redis BRPOP command is as follows :-

Syntax :-

redis host:post> BRPOP <keyname-1> [ <keyname> ] <timeout>

Output :-

- (array) reply, two elements are returned where first element is name of the popped element key
  and second element is the popped element itself.
- (nil), when no element could be popped and timeout is expired.

Example :-

Redis BRPOP

References :-

  1. RPOP Command Docs
  2. BRPOP Command Docs

That’s all for how to remove and return the last element of the list value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.

<- List Commands