Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Combine specified elements of two lists into a new list
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. |
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]= |
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]= |
AlternateElements only works with two lists at a time:
| In[15]:= | ![]() |
| In[16]:= |
| Out[16]= |
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]= |
This work is licensed under a Creative Commons Attribution 4.0 International License