Attempting to combine 1 & 2 dimensional list/arrays containing strings using the insert()
method.
However getting a specific element from the 1D list and placing that into a specific location within the 2D list is where Im stuck.
Here is a simplified version of what the goal is;
#2D list/array
list1= [['a1','b1'], ['a2','b2'] , ['a3','b3']]
#1D list/array
list2= ['c3','c2','c1']
#desired output
list1= [['a1','b1','c1'], ['a2','b2','c2'] , ['a3','b3','c3']]
Here is the isolated block of code from the script which Im trying to attempt this with;
#loop through 1D list with a nested for-loop for 2D list and use insert() method.
#using reversed() method on list2 as this 1D array is in reverse order starting from "c3 -> c1"
#insert(2,c) is specifying insert "c" at index[2] location of inner array of List1
for c in reversed(list2):
for letters in list1:
letters.insert(2,c)
print(list1)
output of the code above;
[['a1', 'b1', 'c3', 'c2', 'c1'], ['a2', 'b2', 'c3', 'c2', 'c1'], ['a3', 'b3', 'c3', 'c2', 'c1']]
What is the best & most efficient way to go about returning the desired output? Should I use the append()
method rather than insert()
or should i introduce list concatenation before using any methods?
Any insight would be appreciated!
As discussed in the comments, you can achieve this via a list comprehension using
enumerate
orzip
. You can useenumerate
to get the index and sublist fromlist1
, using theindex
to select the appropriate value fromlist2
to append to each sublist:or you can
zip
togetherlist1
and the reversedlist2
:Or you can just use a simple
for
loop to modifylist1
in place:For all of these the output is: