What is fromfunction() from numpy in Python?

Overview

The fromfunction() function in Python constructs an array by executing a function over each coordinate. The output array has a value fn(x, y, z) at the (x, y, z) coordinate.

Syntax

numpy.fromfunction(function, shape, *, dtype=<class 'float'>)

The fromfunction() function takes the following parameter values:

  • function: This represents the function called with N parameters. Here, N represents the rank of the shape.

  • shape: This represents an output array’s shape. This also determines the shape of the coordinate arrays passed to function.

  • dtype: This represents the data type of the coordinate arrays passed to function. This is optional, and by default, dtype is a float.

Return value

fromfunction() outputs an array. The result of the call to function is passed back directly. Therefore, the shape of the output array is completely determined by function.

Code example

import numpy as np
# implementing the fromfunction() function
myarray = np.fromfunction(lambda x, y: x + y, (2, 2), dtype=int)
print(myarray)

Code explanation

  • Line 1: We import the numpy module.

  • Line 4: We implement the fromfunction() function on a lambda function that has a 2D array with an integer data type. We assigned the output to a variable, myarray.

  • Line 6: We print myarray.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources