Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
06-28-2022 04:12 PM
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.
Solved! Go to Solution.
06-29-2022 12:31 AM
Hi @tms ,
You are just missing the fact that indexing and slicing are two different things on list comprehensions.
Take a look on https://towardsdatascience.com/mastering-indexing-and-slicing-in-python-443e23457125
You want something like:
WITH
RANGE(1,10) AS indices
WITH
indices[-1] AS lastIndex,
indices[-3..] AS lastThreeIndices
RETURN
lastIndex,
lastThreeIndices
06-29-2022 12:31 AM
Hi @tms ,
You are just missing the fact that indexing and slicing are two different things on list comprehensions.
Take a look on https://towardsdatascience.com/mastering-indexing-and-slicing-in-python-443e23457125
You want something like:
WITH
RANGE(1,10) AS indices
WITH
indices[-1] AS lastIndex,
indices[-3..] AS lastThreeIndices
RETURN
lastIndex,
lastThreeIndices
06-29-2022 07:21 AM
I missed that '..' is Cypher's way of spelling the Python ':' (slice) operator. 🙂
That works, I appreciate the quick response.
All the sessions of the conference are now available online