indexing from the end in a list
maru
Hi,
Can I index an item from the end of a list?
If I have a list {A, B, C, D},
can I use -2 to specify C?
Hi,
Can I index an item from the end of a list?
If I have a list {A, B, C, D},
can I use -2 to specify C?
No, sorry.
It is also good to note that Igor's compiler knows nothing about optimization, so if you are going to access list items at the end repeatedly, it is better to store the list length in a variable. So this:
Variable i
for (some sort of loop)
String oneitem = StringFromList(nitems-2, theList)
endfor
is to be preferred over this:
for (some sort of loop)
String oneitem = StringFromList(ItemsInList(theList)-2, theList)
endfor
The second version will repeatedly walk through the entire list counting the items, the walking through the list looking for requested item. The first version still has to walk through the list looking for the requested item, but doesn't have to count the items again.
But be careful about removing items from the list! In that case, storing nitems can lead to bugs!
March 2, 2020 at 09:57 am - Permalink
I should also note that in some cases it may be more efficient to put your list items in a text wave. Those items can be found without walking through the list.
March 2, 2020 at 09:58 am - Permalink
In reply to I should also note that in… by johnweeks
Thanks!
March 2, 2020 at 10:29 pm - Permalink