Redis LINDEX Command Explained

In Redis, the LINDEX command returns the element at the specified index at the specified key.

Syntax

The syntax goes like this:

LINDEX key index

Where key is the key that holds the list and index is the index of the element to return.

Example

Suppose we create the following list:

RPUSH animals Cat Dog Horse Zebra Rhino

Result:

(integer) 5

We just created a list with five elements.

Let’s take a look at the list first:

LRANGE animals 0 -1

Result:

1) "Cat"
2) "Dog"
3) "Horse"
4) "Zebra"
5) "Rhino"

Now let’s use LINDEX to return one of those values:

LINDEX animals 2

Result:

"Horse"

Lists are zero based, and so 2 returns the third element.

Negative Indices

Entering a negative index results in the index being counted backwards from the tail of the list:

LINDEX animals -2

Result:

"Zebra"

When doing this the count starts at -1 (i.e. it doesn’t start at 0). In other words, using -1 returns the last element in the list.

Non-Existent Element

If the list doesn’t have an element at the specified index, nil is returned:

LINDEX animals 10

Result:

(nil)

Non-Existent Key

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

LINDEX oops 10

Result:

(nil)

Wrong Key Type

If the key exists, but it doesn’t contain a list, an error is returned:

LINDEX username 10

Result:

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

We can check the key type with the TYPE command:

TYPE username

Result:

string

It’s a string, hence the reason we got an error.