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:
-
Zero-based indexing: The first element in the list is at index
0. The second is at1, and so on.- For example, if you have a list
[A, B, C]:Ais at index0Bis at index1Cis at index2
- For example, if you have a list
-
Positive indices: When you use positive integers for
startandend, they refer to elements from the beginning of the list.LRANGE mylist 0 0would return just the first element.LRANGE mylist 0 2would return the first three elements (indices 0, 1, and 2).
-
Negative indices: You can also use negative indices, which count from the end of the list.
-1refers to the last element.-2refers to the second to last element.- And so on.
- For example,
LRANGE mylist -1 -1returns only the last element. LRANGE mylist -2 -1would return the last two elements.
-
Inclusive range: Both the
startandendindices are inclusive. This means that the element at thestartindex and the element at theendindex are both included in the result. -
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 -1correctly returned:1) "item3" (index 0) 2) "item2" (index 1) 3) "item1" (index 2, or -1 from the end) -
LRANGE mylist 0 2returned:1) "item5" 2) "item4" 3) "item3"After you added
item4anditem5, the list became[item5, item4, item3, item2, item1]. So0 2gives you the first three elements. -
LRANGE mylist -1 -1returned: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!