vostro.beta
vostro.beta

Reputation: 303

How do I insert a value to a list which is already in a list?

I want to create a list, which does not already exist. So, i want to use the insert function to insert "0" as the new element in that list.

The problem ist that I don't know how to access the index of the element position which is in a nested list.

I have tried to resolve my problem using : matrix_result[i1].insert(i2, 0)

but it does not help me and the programm gives an error because of this line. Full code:

matrix1 = [[1, 5], [6, 4]]
matrix2 = [[3, 2], [7, 8]]
matrix_result = []


def add(p1, p2):
    global matrix_result

    for i1 in range(0, len(p1)):
        matrix_result.insert(i1,0)
        for i2 in range(0, len(p1[i1])):
            matrix_result[i1].insert(i2, 0)
            matrix_result[i1][i2] = p1[i1][i2] + p2[i1][i2]
    return matrix_result


print(add(matrix1, matrix2))

Expected result: the matrix_result has exact many elements as there are in matrix1 but all with the value 0

actual result: error because of the statement : matrix_result[i1].insert(i2, 0)

Upvotes: 2

Views: 88

Answers (6)

Sharu
Sharu

Reputation: 77

If you're trying to implement matrix addition, I assume that you want the following behaviour:

# m1 = [[1, 5], [6, 4]]
# m2 = [[3, 2], [7, 8]]
# add(m1, m2) => [[4, 7], [13, 12]]

If you can't use any libraries, you could use zip and map, where we also assume that the dimensions of the matrices are the same of course:

def add(p1, p2):
  adder = lambda tuple: [tuple[0][i] + tuple[1][i] for i in range(len(tuple[1]))]
  return list(map(adder, zip(p1, p2)))

print(add(matrix1, matrix2))
# [[4, 7], [13, 12]]

The simplest and fastest would be to use numpy:

import numpy as np 

def add(p1, p2):
    return np.array(p1) + np.array(p2) 

Upvotes: 0

mad_
mad_

Reputation: 8273

Change the matrix_result to contain list of lists. Also problem in your solution is you are accessing the int type saved in the list matrix_result[i1] and trying to insert in the int type which is not possible using insert(i2, 0)

matrix1 = [[1, 5], [6, 4]]
matrix2 = [[3, 2], [7, 8]]
matrix_result = [[0,0],[0,0]]

def add1(p1, p2):
    global matrix_result

    for i1 in range(len(p1)):
            for i2 in range(len(p1[i1])):  
                matrix_result[i1][i2] = p1[i1][i2] + p2[i1][i2]
    return matrix_result
print(add1(matrix1, matrix2))

Although you do not necessarily need insert() here but if you really want to then below is the updated version of your code

matrix1 = [[1, 5], [6, 4]]
matrix2 = [[3, 2], [7, 8]]
matrix_result = [[],[]]


def add1(p1, p2):
    global matrix_result

    for i1 in range(0, len(p1)):

        for i2 in range(0, len(p1[i1])):
            matrix_result[i1].insert(i2,0)
            matrix_result[i1][i2] = p1[i1][i2] + p2[i1][i2]
    return matrix_result

print(add1(matrix1, matrix2))

Upvotes: 0

user8866053
user8866053

Reputation:

Your empty list matrix_result presented a few challenges to the interpreter. I made a few changes to your code and the matrices add.

matrix1 = [[1, 5], [6, 4]]
matrix2 = [[3, 2], [7, 8]]
matrix_result = [[0,0], [0,0]] # CHANGE: empty array is now zeroes


def add_matrix(p1, p2):
    global matrix_result

    for i1 in range(0, len(p1)):
        for i2 in range(0, len(p1[i1])):
            matrix_result[i1][i2] = 0 # change: no .insert(), just assignment. you can (and probably should) remove this line.
            matrix_result[i1][i2] = p1[i1][i2] + p2[i1][i2]
    return matrix_result


print(add_matrix(matrix1, matrix2))

I hope this helps you!

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26315

I don't think you need to use insert() here. An easier way would be to use zip():

matrix1 = [[1, 5], [6, 4]]
matrix2 = [[3, 2], [7, 8]]

def add(*args):
    matrix_result = []

    for pair in zip(*args):
        inner = []
        for x, y in zip(*pair):
            inner.append(x + y)
        matrix_result.append(inner)

    return matrix_result

print(add(matrix1, matrix2))
# [[4, 7], [13, 12]]

You can also use a list comprehension:

def add(*args):
    return [[x + y for x, y in zip(*pair)] for pair in zip(*args)]

Upvotes: 0

Xteven
Xteven

Reputation: 441

I want to create a list, which does not already exist. So, i want to use the insert function to insert "0" as the new element in that list.

You cannot insert to a non-existent list. You have to use [] to first create the list, then you can insert things into it.

Solution: On the line where you say matrix_result.insert(i1, 0), you insert an int instead of a list. To insert an empty list, you have to say matrix_result.insert(i1, []).

EDIT: As Jondiedoop has said, it is usually recommended to use the numpy library for matrix operations because it is highly optimized and easy to use. Go here for more information: NumPy.org

Upvotes: 2

Jondiedoop
Jondiedoop

Reputation: 3353

For all matrix manipulations, use the numpy-library:

import numpy as np
np.array(matrix1) + np.array(matrix2)

Output:

#array([[ 4,  7],
#      [13, 12]])

Apart from being much easier and much more flexible, it will also be much faster.

Upvotes: 3

Related Questions