How are indices in LRANGE defined?

QuestionsQuestions8 SkillsProDec, 16 2025
0172

Hello there! I'm Labby, and it looks like you're diving into Redis Lists and specifically asking about how indices work with the LRANGE command. That's a great question, as understanding indexing is key to effectively using lists!

In Redis's LRANGE command:

  1. Zero-based indexing: The first element in the list is at index 0. The second is at 1, and so on.

    • For example, if you have a list [A, B, C]:
      • A is at index 0
      • B is at index 1
      • C is at index 2
  2. Positive indices: When you use positive integers for start and end, they refer to elements from the beginning of the list.

    • LRANGE mylist 0 0 would return just the first element.
    • LRANGE mylist 0 2 would return the first three elements (indices 0, 1, and 2).
  3. Negative indices: You can also use negative indices, which count from the end of the list.

    • -1 refers to the last element.
    • -2 refers to the second to last element.
    • And so on.
    • For example, LRANGE mylist -1 -1 returns only the last element.
    • LRANGE mylist -2 -1 would return the last two elements.
  4. Inclusive range: Both the start and end indices are inclusive. This means that the element at the start index and the element at the end index are both included in the result.

  5. Retrieving all elements: To get all elements in a list, you use LRANGE key 0 -1. This tells Redis to start from the first element (index 0) and go all the way to the last element (index -1).

Let's look at the example from the step:

After running:

LPUSH mylist item1
LPUSH mylist item2
LPUSH mylist item3

Your mylist conceptually looks like: [item3, item2, item1] (because LPUSH adds to the head/left).

  • LRANGE mylist 0 -1 correctly returned:

    1) "item3"  (index 0)
    2) "item2"  (index 1)
    3) "item1"  (index 2, or -1 from the end)
  • LRANGE mylist 0 2 returned:

    1) "item5"
    2) "item4"
    3) "item3"

    After you added item4 and item5, the list became [item5, item4, item3, item2, item1]. So 0 2 gives you the first three elements.

  • LRANGE mylist -1 -1 returned:

    1) "item1"

    Which is indeed the last element of the list.

Is there anything specific about LRANGE indices that you'd like to clarify further? I'm here to help!

0 Comments

no data
Be the first to share your comment!