Redis LPOP Command Explained

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

By default, the command pops a single element from the beginning 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:

LPOP 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 first element like this:

LPOP scores

Result:

"1"

That is the value of the element that was popped.

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

LRANGE scores 0 -1

Result:

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

Pop Multiple Elements

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

Example:

LPOP scores 3

Result:

1) "2"
2) "3"
3) "4"

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) "5"
2) "6"
3) "7"
4) "8"
5) "9"
6) "10"

We’ve now got just six elements remaining.

Wrong Type

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

LPOP customer

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 customer

Result:

hash

In this case it’s a hash.

Non-Existent Key

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

LPOP nonexistentkey

Result:

(nil)