Search code examples
pythonlistmultiplication

How can I multiply all the elements in a list with a given constant?


 [[[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]]]

I want to multiply all the numbers in this list using Python with a constant (say (-1)), but the list still has the original format. I was trying to do that with 3 'for' loops, but is there a short way I can do this? Thanks!!


Solution

  • The following code can multiply all of the numbers by a constant. For more advanced operations, you may want to look into np.vectorize or np.apply

    import numpy as np
    
    nested_list = [[[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]]]
    numpy_list = np.array(nested_list)
    
    negated_list = -1 * numpy_list