Follow List Values to Determine Next Index in Grasshopper

Hi everyone,
I need help solving a problem in Grasshopper. I need to transform the list on the left into the list on the right, following a specific sequence rule. Here’s the rule:

  • Start with the first item in the list (5).
  • Use its value to determine the next index to visit (5th item).
  • From there, retrieve the value (6) and use it to determine the next index (6th item is 8).
  • Continue this process until all items are visited.

Can anyone help me find a solution in Grasshopper?

If you don’t mind using ghPython, this is what you asked for:

def main(input):
    result = []
    index = 0
    for _ in range(len(input)):
        result.append(input[index])
        index = input[index]
    return result

result = main(input)

Essentially you want to loop through the results and use the value of the previous output as the index of the new one. The easiest one I can think of (yet not very scalable) is using list item > index of the new list item. See image below. However as you might want to expand the list it’s best to look for a loop solution.

With Python it’s simpler but you can also do it without.

A non-iterative solution by exploiting “preserve direction” of the join component, without plugins or typed code:


navigate indexes.gh (9.2 KB)

… just to mess around.

5 Likes

Thank you all for your help! I’ve successfully solved the problem. The code ended up looking simpler than I thought, and all the solutions shared were great.

I really appreciate the time and effort you took to assist me.