Search code examples
listpython-2.7matrix2d

Python list with multiple 2D list append same value to first row of each value


I have a list like this:

a = [[[0, 1], [1, 1]], [[1, 0], [1, 1]]]

Which means i have two 2D list inside a list:

a[0] = [0, 1], [1, 1]           

a[1] = [1, 0], [1, 1]

and i would like to append the same value to the first and second row (let's say [0, 1]) for both 2D list at the same time; resulting in something like this:

a[0] = [0, 1, 0], [1, 1, 1]           


a[1] = [1, 0, 0], [1, 1, 1]

i don't want to do it becuase i am trying to improve the time spent in loops.

I have been doing it this way:

        elif (rown == 0) and (columnn > 0):
            s_routine = time.time()
            p_temp = p[:]
            p = []
            for matrix in p_temp:
                ca = matrix[0][columnn]
                cb = matrix[1][columnn]
                if columnv == 0:
                    zl = zfc[str(ca)+str(cb)]
                    for z in zl:
                        a = matrix[0] + [z[0][1]]
                        b = matrix[1] + [z[1][1]]
                        c = [a, b]
                        p.append(c)
                elif columnv == 1:
                    ol = zfc[str(ca)+str(cb)]
                    for o in ol:
                        a = matrix[0] + [o[0][1]]
                        b = matrix[1] + [o[1][1]]
                        c = [a, b]
                        p.append(c)
            e_routine = time.time() - s_routine

But the matrix is growing too much and therefore the loops are taking a lot.


Solution

  • I think you can do this easier, for example:

    a = [[[0, 1], [1, 1]], [[1, 0], [1, 1]]]
    
    for row in a:
        for subl, v in zip(row, [0, 1]):
            subl.append(v)
    
    print(a)
    

    Prints:

    [[[0, 1, 0], [1, 1, 1]], [[1, 0, 0], [1, 1, 1]]]