Redis LRANGE Command Explained

In Redis, the LRANGE command returns the specified elements of the list stored at the specified key.

The command requires us to specify a start and stop position for the elements to return. These are zero based indexes, so 0 is the first element in the list.

We can specify -1 for the last element in the list.

Syntax

The syntax goes like this:

LRANGE key start stop

Where key is the key that contains the list, start is the first element we want to return, and stop is the last element we want to return.

Example

Suppose we create the following list:

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

Result:

(integer) 10

The list contains 10 elements.

We can use the LRANGE command to return one or more elements from our list. For example:

LRANGE scores 0 2

Result:

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

In this case, we returned the first three elements. Lists are zero based, and so 0 is the first element and 2 is the third.

Here’s another example, this time starting further along the list:

LRANGE scores 3 7

Result:

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

Return All List Elements

We can return all list items by specifying 0 and -1:

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"

Negative Indexes

As shown in the previous example, using -1 as the third argument specifies the end of the list. This is because negative values count backwards from the end of the list. Therefore, if we wanted to return the penultimate value (second last value), we could use -2:

LRANGE scores 0 -2

Result:

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

And we can specify -3 for the third last value, and so on.

Out of Range Indexes

If the ending position is greater than the end of the list, then it’s treated as thought it’s the last element in the list:

LRANGE scores 5 20

Result:

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

If the starting position is greater than the end of the list, then an empty list is returned:

LRANGE scores 20 25

Result:

(empty array)