What are lists in Redis?

In Redis, Lists store an ordered sequence of strings.

We can use the following commands to add elements from lists in Redis:

The LPUSH command

The LPUSH command is used to add elements at the beginning of the list.

Before carrying out the push operations, an empty list is generated if it does not already exist. An error is produced if the key contains a value that is not a list.

Syntax

The syntax is as follows:

LPUSH key value1 ... valueN

Parameters

  • key: This is the name under which the list is registered.
  • value[X]: This is the value to be added to the list.

The RPUSH command

The RPUSH command is used to append the elements to the list.

Before carrying out the push operations, an empty list is generated if it does not already exist. An error is produced if the key contains a value that is not a list.

Syntax

The syntax is as follows:

RPUSH key value1 ... valueN

Parameters

  • key: This is the name under which the list is registered.
  • value[X]: These are the values to be added to the list.

We can use the following commands to remove elements from lists in Redis:

The LPOP command

The LPOP command is used to remove elements from the beginning of the list.

By default, the command removes a single element from the beginning of the list. With the help of the count option, we can specify the number of elements to be removed.

Syntax

The syntax is as follows:

LPOP key [count]

Parameters

  • key: This is the name under which the list is registered.
  • count: This is the number of elements to be removed.

The RPOP command

The LPOP command is used to remove elements from the end of the list.

By default, the command removes a single element from the end of the list. We can specify the number of elements to be removed With the help of the count option.

Syntax

The syntax is as follows:

RPOP key [count]

Parameters

  • key: This is the name under which the list is registered.
  • count: This is the number of elements to be removed.

Some of the other common commands are as follows:

The LLEN command

The LLEN command is used to return the length of the list.

Syntax

The syntax is as follows:

LLEN key

Parameters

  • key: This is the name under which the list is registered.
LPUSH lst hi hello educative
LLEN lst
LPOP lst
RPUSH lst new-hi new-hello
RPOP lst

We can run the above commands in the following terminal:

Terminal 1
Terminal
Loading...
Copyright ©2024 Educative, Inc. All rights reserved