Wolfram Research

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

Frequently used for when a large list of items needs to be transformed but the original indices have to be preserved.

Examples

Basic Examples

Add indices to a list of elements:

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

Scope

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

Select palindromic words from a Select 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

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]=

Resource History

See Also

License Information