Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

attribute
numpy
array
python
communitycreator

What is the shape attribute of numpy in Python?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The shape attribute in numpy is used to return a tuple with the index numbers representing the dimension or shape of the given array.

Syntax

array.shape

Parameter

array.shape is an attribute and therefore takes no parameter value.

Return value

array.shape returns the shape [dimension of the 2D array (row, column)] of a given array.

Example

from numpy import array

# creating an array
my_array = array([[1, 2, 3, 4], [5, 6, 7, 8]])

# to return the shape of the array
print(my_array.shape)
Implementing the shape attribute

Explanation

  • Line 1: We import the array from the numpy library.
  • Line 4: We create an array using the array() method.
  • Line 7: We implement the shape attribute to determine the shape of the array my_array and print the output.

The output of the code is (2,4), which means that the array my_array we created is a two-dimensional array. The first has 2 elements while the second has 4 elements.

Let’s try out another example:

Example

from numpy import array

my_array = array([1, 2, 3, 4])

print(my_array.shape)
Implementing the shape attribute

Code explanation

The output of the code above (4,) means that the array my_array is a one-dimensional array with 4 elements.

RELATED TAGS

attribute
numpy
array
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring