0

I want to join two lists which are in the following form:

a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]]
b=[[55,66,99],[77,88,44],[100,101,100]]

Such that the result is:

result =[[[55,1,2,3],[66,4,5,6],[99,7,8,9]],[[77,11,21,31],[88,14,15,16],[44,17,18,19]],[[100,41,42,43],[101,48,45,46],[100,76,86,96]]]

I tried doing this, but it does not work

for i in range(len(a)): 
    for j in range(len(a[i])):
        a[i][j].insert(0, b[i][j])

a
ash90
  • 123
  • 9

2 Answers2

0

try this code:

a=[[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]]
b=[[55,66,99],[77,88,44],[100,101,100]]
for i in range(0,3):
    for j in range(0,3):
        result = a[i][j]
        result.insert(0, b[i][j])
        print(result)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Usama Aleem
  • 113
  • 7
  • Welcome to SO, we appreciate your input! Please edit your question according to https://stackoverflow.com/help/how-to-answer and explain a bit your code, why it answers the question, how it works, ... – B--rian Aug 18 '19 at 21:04
0

First of all, I would suggest not to change an iterable you're iterating over. You can read more at Modifying list while iterating.

Secondly, I want to propose using a nested loops with zip functions for a solution:

a = [[[1,2,3],[4,5,6],[7,8,9]],[[11,21,31],[14,15,16],[17,18,19]],[[41,42,43],[48,45,46],[76,86,96]]]
b = [[55,66,99],[77,88,44],[100,101,100]]
c = []

for i, j in zip(a, b):
    for k, m in zip(i, j):
        c.append([m] + k)  # k.insert(0, m) if you want to change k in-place (not recommended)

The outer loop iterates over first-level nested lists in a and over lists in b. The inner loop iterates over second-level lists in a and over integers in b. The values are merged into a single list that will be appended to a c.

You can read more about zip function at https://docs.python.org/3/library/functions.html#zip.