Function Repository Resource:

AddIndices

Source Notebook

Pairs each element of a list with its index

Contributed by: Sander Huisman

ResourceFunction["AddIndices"][{e1,e2,}]

pairs each ei with its index i forming the list {{1,e1},{2,e2},}.

ResourceFunction["AddIndices"][{e1,e2,},imin]

pairs each ei with its index starting from imin forming the list {{imin,e1},{imin+1,e2},}.

ResourceFunction["AddIndices"][{e1,e2,},imin,di]

uses step di forming the list {{imin,e1},{imin+di,e2},}.

Details and Options

ResourceFunction["AddIndices"] is frequently used when a large List of items needs to be transformed, but the original indices must be preserved.

Examples

Basic Examples (1) 

Add indices to a List of elements:

In[1]:=
ResourceFunction["AddIndices"][{a, b, c, d}]
Out[1]=

Scope (2) 

Start with the index 4:

In[2]:=
ResourceFunction["AddIndices"][{a, b, c, d}, 4]
Out[2]=

The starting index and the step can be symbolic. Start the index at x:

In[3]:=
ResourceFunction["AddIndices"][{a, b, c, d}, x]
Out[3]=

The step can also be symbolic:

In[4]:=
ResourceFunction["AddIndices"][{a, b, c, d}, x, y]
Out[4]=

Applications (2) 

Use Select to choose palindromic words while retaining their indices:

In[5]:=
s = {"anna", "has", "a", "red", "racecar", ",", "wow", "!"};
s = ResourceFunction["AddIndices"][s];
s = Select[s, Last/*PalindromeQ]
Out[7]=

Sort the strings and retain their original indices:

In[8]:=
s = {"anna", "has", "a", "red", "racecar", ",", "wow", "!"};
s = ResourceFunction["AddIndices"][s];
SortBy[s, Last]
Out[10]=

Properties and Relations (2) 

The functionality of AddIndices can be achieved using MapIndexed:

In[11]:=
MapIndexed[{#2[[1]], #1} &, {a, b, c, d, e}] === ResourceFunction["AddIndices"][{a, b, c, d, e}]
Out[11]=

AddIndices is roughly 4 times faster:

In[12]:=
ele = RandomReal[{0, 1}, 10^5];
{First[RepeatedTiming[MapIndexed[{#2[[1]], #1} &, ele];]], First[RepeatedTiming[ResourceFunction["AddIndices"][ele];]]}
Out[13]=

Publisher

SHuisman

Version History

  • 1.0.0 – 03 July 2019

Related Resources

License Information