Function Repository Resource:

AlternateElements

Combine specified elements of two lists into a new list

Contributed by: Claudio Lobo Chaib Filho
 ResourceFunction["AlternateElements"][list1,list2] intersperses elements in odd positions from list1 with elements in even positions from list2. ResourceFunction["AlternateElements"][list1,list2,pattern] alternates between the lists using the specified pattern (e.g. {2,1,2,2,1}), where the positions of each value in pattern determine where to take from list1 and list2 respectively.

Details and Options

Unlike Riffle, ResourceFunction["AlternateElements"] omits elements from positions in list1 that are included from list2 and vice versa.
By default, ResourceFunction["AlternateElements"] operates by choosing one term from each list in an alternating fashion. However, it is possible to specify a pattern, for example {1,2,1,1,2}, as a third argument.

Examples

Basic Examples (2)

This is a simple example of how AlternateElements works:

 In[1]:=
 In[2]:=
 Out[2]=

AlternateElements also works with non-numeric terms:

 In[3]:=
 In[4]:=
 Out[4]=

Scope (4)

AlternateElements works with lists of different sizes, keeping all elements from the end of the longer list once the shorter list is exhausted:

 In[5]:=
 In[6]:=
 Out[6]=
 In[7]:=
 Out[7]=

An example with a new pattern chosen:

 In[8]:=
 In[9]:=
 Out[9]=

Use a list from a binary number as a pattern:

 In[10]:=
 In[11]:=
 Out[11]=
 In[12]:=
 Out[12]=

AlternateElements can also be used with a random pattern:

 In[13]:=
 In[14]:=
 Out[14]=

Possible Issues (1)

AlternateElements only works with two lists at a time:

 In[15]:=
 In[16]:=
 Out[16]=

Neat Examples (2)

As a practical use of AlternateElements, you can create hybrid numbers of a given length with alternating digits taken from two real constants. This example illustrates that technique using Pi and E:

 In[17]:=
 In[18]:=
 In[19]:=
 Out[19]=
 In[20]:=
 Out[20]=

Here is a similar example with a nondefault pattern:

 In[21]:=
 In[22]:=
 Out[22]=
 In[23]:=
 Out[23]=

Publisher

Claudio Lobo Chaib Filho

Version History

• 1.0.0 – 21 June 2019

Author Notes

Only works at two lists at a time ( just as the definition already typifies ). Can work with other characters, but not with strings.