0
0
RedisHow-ToBeginner · 3 min read

How to Use LREM Command in Redis: Syntax and Examples

Use the LREM command in Redis to remove elements from a list by specifying the list key, the number of occurrences to remove, and the value to remove. The syntax is LREM key count value, where count controls how many matching elements are removed and their direction.
📐

Syntax

The LREM command removes elements from a Redis list by value.

  • key: The name of the list.
  • count: Number of occurrences to remove. Positive to remove from head to tail, negative from tail to head, zero removes all.
  • value: The element value to remove.
redis
LREM key count value
💻

Example

This example shows how to remove elements from a list using LREM. It removes up to 2 occurrences of the value "apple" from the list "fruits" starting from the head.

redis
127.0.0.1:6379> RPUSH fruits apple banana apple orange apple
(integer) 4
127.0.0.1:6379> LRANGE fruits 0 -1
1) "apple"
2) "banana"
3) "apple"
4) "orange"
5) "apple"
127.0.0.1:6379> LREM fruits 2 apple
(integer) 2
127.0.0.1:6379> LRANGE fruits 0 -1
1) "banana"
2) "orange"
3) "apple"
Output
2 1) "banana" 2) "orange" 3) "apple"
⚠️

Common Pitfalls

Common mistakes when using LREM include:

  • Using count incorrectly: a positive count removes from the start, negative from the end, zero removes all matching elements.
  • Expecting LREM to remove by index instead of value.
  • Not checking if the list exists before calling LREM, which returns 0 if the list is missing.
redis
127.0.0.1:6379> LREM fruits -1 apple
(integer) 1
127.0.0.1:6379> LREM fruits 0 apple
(integer) 1
Output
1 1
📊

Quick Reference

ParameterDescription
keyThe list key from which to remove elements
countNumber of occurrences to remove: positive (head to tail), negative (tail to head), zero (all matches)
valueThe element value to remove from the list

Key Takeaways

LREM removes elements by value from a Redis list based on count direction and number.
A positive count removes from the start; negative from the end; zero removes all matching elements.
LREM returns the number of removed elements, zero if none found or list missing.
Always specify the exact value to remove; LREM does not remove by index.
Check your list contents with LRANGE before and after using LREM to verify changes.