How can I append this elements to an array in python?
<pre><code>input_elements = ["a", "b", "c", "d"]
my_array = ["1", "2", "3", "4"]
</code></pre>

<p>the output I want is:</p>

<pre><code>["1", "2", "3", "4", "a"]
["1", "2", "3", "4", "b"]
["1", "2", "3", "4", "c"]
["1", "2", "3", "4", "d"]
</code></pre>

<p>I tried:</p>

<pre><code>for e in input_elements:
  my_array.append(e)
</code></pre>

<p>I know the code right above is wrong, so I am wondering how I can generate the output like that.</p>

<p>I'm assuming the output you're getting is:</p>

<pre><code>['1', '2', '3', '4', 'a', 'b', 'c', 'd']
</code></pre>

<p>...because, that's what I'm getting.</p>

<p>The problem is, in your loop, you're simply adding a new element to the existing array, then printing the "grand total."  So, you add a, then you add b, then you add c, then d... all to the same array, then printing out the whole shebang.</p>

<p>The easiest solution for your particular problem is, in your for loop, print the array as it is, with the <code>e</code> selection concatenated.  Like so:</p>

<pre><code>input_elements = ["a", "b", "c", "d"]
my_array = ["1", "2", "3", "4"]

for e in input_elements:
  print my_array + [e]
</code></pre>

<p>That way, you're printing the array with the extra element, without actually affecting the original array... keeping it "clean" to loop back through and add the next element.</p>

<p>This method allows you to achieve the desired result without having to result to extra memory allocation or unnecessary variables.</p>

<p>If you have other things to do during the <code>for</code> loop, you could always add the element, then remove it after processing using the <code>pop</code> function, like so:</p>

<pre><code>for e in input_elements:
  my_array.append(e)
  print my_array
  # Do some other nifty stuff
  my_array.pop()
</code></pre>

<p>Another option is to use List Comprehension, which allows you to iterate through an array as more of an inherent statement:</p>

<p><code>print [my_array+[e] for e in input_elements]</code></p>

python list