Skip to the workspace
Pebellslearn by building
Lists  ›  Lesson

LRANGE, LINDEX and LLEN

LRANGE 12 minLRANGE reads a slice of a list by inclusive start and stop indexes, LINDEX reads one position, LLEN counts items, and negative indexes count back from the tail.

redis / LRANGE, LINDEX and LLEN

Explore each scene at your own pace.

01 · The rule

The rule

LRANGE, LINDEX and LLEN

Asha's activity feed has grown to hundreds of entries, but her profile only shows the latest five, a "see more" page shows the next five, and a badge says how many there are in total. You never want the whole list; you want a slice, one item, or a count.

The rule

Indexes start at 0 from the head and -1 from the tail; LRANGE includes both ends.

feed:asha holds, from head to tail: won, lost, won, joined, won.

Item won lost won joined won
From head 0 1 2 3 4
From tail -5 -4 -3 -2 -1
127.0.0.1:6379> LRANGE feed:asha 0 1
1) "won"
2) "lost"
127.0.0.1:6379> LRANGE feed:asha -2 -1
1) "joined"
2) "won"
127.0.0.1:6379> LINDEX feed:asha 3
"joined"
127.0.0.1:6379> LINDEX feed:asha 9
(nil)
127.0.0.1:6379> LLEN feed:asha
(integer) 5
  • LRANGE key start stop returns the items from start to stop, both included. 0 -1 is the whole list.
  • An index past the end is clipped, not an error: LRANGE feed:asha 3 100 returns just joined, won. If start is already past the end, or after stop, the reply is an empty list.
  • LINDEX key index returns one item, or (nil) if there is nothing at that index.
  • LLEN key counts the items; a missing key has length 0.

Paging a feed. Page 1 is LRANGE feed:asha 0 4, page 2 is LRANGE feed:asha 5 9. In general, page n of size 5 is start = 5 × (n − 1) and stop = start + 4.

A note on speed. Reading near either end is instant. LINDEX in the middle of a very long list has to walk to that position, so lists are best used from their ends; for "is X in here?" a set is the right tool.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.