cancel
Showing results for
Did you mean:

## Unexpected list index behavior

Graph Buddy

I am seeing unexpected list index behavior while using negative indices.

Here is a trivial list:

``````WITH
RANGE(1,10) AS indices
RETURN
indices``````

I would like to answer the last item of the list as well as the last three items.

I therefore use the following cypher:

``````WITH
RANGE(1,10) AS indices
WITH
indices[-1] AS lastIndex,
indices[-4..-1] AS lastThreeIndices
RETURN
lastIndex,
lastThreeIndices``````

When I run this in the Neo4J Browser, I see an answer of  10, as expected, for lastIndex.

I get the following as the value of lastThreeIndices:

``[7, 8, 9]``

I expect to see

``[8, 9, 10]``

If indices[-1] gives the correct answer (the last element of the list), then how can it be possible for indices[-4..-1] to NOT answer the last three elements of the list?

Am I having a brain-fart? What am I missing?

This is at least unexpected if not simply a bug.

1 ACCEPTED SOLUTION
Neo4j

Hi @tms ,

You are just missing the fact that indexing and slicing are two different things on list comprehensions.

You want something like:

``````WITH
RANGE(1,10) AS indices
WITH
indices[-1] AS lastIndex,
indices[-3..] AS lastThreeIndices
RETURN
lastIndex,
lastThreeIndices``````
Oh, y’all wanted a twist, ey?
2 REPLIES 2
Neo4j

Hi @tms ,

You are just missing the fact that indexing and slicing are two different things on list comprehensions.

You want something like:

``````WITH
RANGE(1,10) AS indices
WITH
indices[-1] AS lastIndex,
indices[-3..] AS lastThreeIndices
RETURN
lastIndex,
lastThreeIndices``````
Oh, y’all wanted a twist, ey?
Graph Buddy

I missed that '..' is Cypher's way of spelling the Python ':' (slice) operator. 🙂

That works, I appreciate the quick response.