How to multiply all elements of an array by number in Python?

Asked

Viewed 289 times

0

I need to do a function that given a matrix and a number, returns the resulting matrix by multiplying all elements of the matrix by that number.

I tried something like this:

def mult(matriz, n):
    resultado = []
    for linha in matriz:
        for elemento in linha:
            resultado = resultado + (elemento * n)
            return resultado

But you’re making a mistake.

  • You want to multiply each element of the matrix by the number?

  • that! ai return the resulting multiplication matrix

1 answer

1


On line 5 of the code, when you do:

resultado = resultado + (elemento * n)

You are trying to use the operator + between two operands of different types. The resultado (first operand) is a list and elemento * n (second operand) is an expression that will be evaluated for number.

It doesn’t make much sense to do this kind of thing, so much so that Python throws a mistake:

TypeError: can only concatenate list (not "int") to list

That is, you can use the + as a concatenation operator between two lists, but not between a list and an integer (as you tried to do).


One way to do this type of operation is to modify the matrix passed from the indexes of each loop. For this purpose, the enumerate:

def mult(matrix, n):
    for lineIndex, line in enumerate(matrix):
        for elementIndex, element in enumerate(line):
            # Modificamos o elemento atual pela multiplicação de `n` e o próprio elemento:
            matrix[lineIndex][elementIndex] = element * n

See working on Ideone.

But note that, with this approach, we are modifying the original matrix (so much so that we do not need to return anything from the function mult. Another option would be to create a new list and add the resulting elements in each iteration. Something like this:

def mult(matrix, n):
    newMatrix = []

    for line in matrix:
        newLine = []  # Criamos uma nova linha

        for element in line:
            newLine.append(element * n)  # Inserimos o produto na nova linha

        newMatrix.append(newLine)  # Inserimos a nova linha na nova matriz

    return newMatrix

See working on Ideone.

And of course, can you make it more concise (and perhaps less understandable? :P) using list comprehensions:

def mult(matrix, n):
    return [[element * n for element in line] for line in matrix]

See working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.