Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 583
Kristine Avatar asked Mar 11 '23 23:03

Kristine


2 Answers

You can use a list comprehension to solve your issue.

>>> input_elements = ["a", "b", "c", "d"]
>>> my_array = ["1", "2", "3", "4"]
>>> [my_array+[i] for i in input_elements]

The result looks like

>>> from pprint import pprint
>>> pprint([my_array+[i] for i in input_elements])
[['1', '2', '3', '4', 'a'],
 ['1', '2', '3', '4', 'b'],
 ['1', '2', '3', '4', 'c'],
 ['1', '2', '3', '4', 'd']]

See What does "list comprehension" mean? How does it work and how can I use it? for more details about them.

like image 65
Bhargav Rao Avatar answered Mar 13 '23 13:03

Bhargav Rao


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]

like image 32
Christine Avatar answered Mar 13 '23 14:03

Christine