w3resource logo
Python Exercises

Python NumPy: Create a function cube which cubes all the elements of an array

Python NumPy: Array Object Exercise-76 with Solution

Write a Python program to create a function cube which cubes all the elements of an array.

Sample Solution:-

Python Code:

import numpy as np
def cube(e):
    it = np.nditer([e, None])
    for a, b in it:
        b[...] = a*a*a
    return it.operands[1]
print(cube([1,2,3]))

Sample Output:

[ 1  8 27]

Python Code Editor:

import numpy as np
def cube(e):
    it = np.nditer([e, None])
    for a, b in it:
        b[...] = a*a*a
    return it.operands[1]
print(cube([1,2,3]))

Improve this sample solution and post your code through Disqus