Kristine Kristine - 1 month ago 8
Python Question

How can I append this elements to an array in python?

input_elements = ["a", "b", "c", "d"]
my_array = ["1", "2", "3", "4"]


the output I want is:

["1", "2", "3", "4", "a"]
["1", "2", "3", "4", "b"]
["1", "2", "3", "4", "c"]
["1", "2", "3", "4", "d"]


I tried:

for e in input_elements:
my_array.append(e)


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

Answer

I'm assuming the output you're getting is:

['1', '2', '3', '4', 'a', 'b', 'c', 'd']

...because, that's what I'm getting.

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.

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

input_elements = ["a", "b", "c", "d"]
my_array = ["1", "2", "3", "4"]

for e in input_elements:
  print my_array + [e]

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.

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

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

for e in input_elements:
  my_array.append(e)
  print my_array
  # Do some other nifty stuff
  my_array.pop()

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

print [my_array+[e] for e in input_elements]