NumPy: Create a function cube which cubes all the elements of an array
Apply Cube Function to All Elements
Write a NumPy program to create a function cube for all array elements.
Pictorial Presentation:

Sample Solution:
Python Code:
Sample Output:
[ 1 8 27]
Explanation:
In the above code -
- def cube(e):: Define a function called cube that takes a single argument e.
- it = np.nditer([e, None]): Create a NumPy iterator called it that iterates over the input array e and an uninitialized output array of the same shape as e. This is done by passing None as the second element in the list.
- for a, b in it:: Iterate over the elements of e and the uninitialized output array using the iterator it. a represents an element from e, and b represents the corresponding element in the output array.
- b[...] = a*a*a: Cube the value of a and assign it to the corresponding element b in the output array.
- return it.operands[1]: After the loop, return the output array, which is stored as the second operand in the iterator it.
- Finally ‘print(cube([1,2,3]))’ prints the result.
For more Practice: Solve these Related Problems:
- Write a NumPy program to apply a cube function to each element of an array using np.vectorize.
- Create a function that computes the cube of array elements and compares the output with manual exponentiation.
- Use np.power to raise each element of an array to the third power and verify the results.
- Implement the cube operation using both list comprehension and vectorized operations, then compare performance.
Go to:
PREV : Zeros Array with Multiple Column Types
NEXT : Chunkify (3,4) Array Elements
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.