Redis RPOP Command Explained

In Redis, the RPOP command removes and returns the last elements of the list stored at the specified key.

By default, the command pops a single element from the end of the list. However, we have the option of passing a second argument that specifies how many elements to pop.

Syntax

The syntax goes like this:

RPOP key [count]

Where key is the key to pop, and [count] is an optional argument that specifies how many elements to pop. Omitting this argument results in a single element being popped.

Example

Suppose we create a list like this:

RPUSH scores 1 2 3 4 5 6 7 8 9 10

Result:

(integer) 10

Let’s look at its contents:

LRANGE scores 0 -1

Result:

 1) "1"
 2) "2"
 3) "3"
 4) "4"
 5) "5"
 6) "6"
 7) "7"
 8) "8"
 9) "9"
10) "10"

We can pop the last element like this:

RPOP scores

Result:

"10"

That is the value of the element that was popped.

Now when we return all elements in the list, we see that the last element is no longer there:

LRANGE scores 0 -1

Result:

1) "1"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"
7) "7"
8) "8"
9) "9"

Pop Multiple Elements

As mentioned, we have the option of passing a second argument that specifies how many elements to pop.

Example:

RPOP scores 3

Result:

1) "9"
2) "8"
3) "7"

In this case we popped the next three elements.

Now let’s take a look at our list again:

LRANGE scores 0 -1

Result:

1) "1"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"

We’ve now got just six elements remaining.

Wrong Type

If the key is the wrong type, an error is returned:

RPOP name

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

We can use the TYPE command to check the key’s type:

TYPE name

Result:

string

In this case it’s a string.

Non-Existent Key

If the key doesn’t exist, nil is returned:

RPOP nonexistentkey

Result:

(nil)