Open In App

NumPy ndarray itemset() Method | Insert Scalar in ndarray

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The NumPy ndarray.itemset() method inserts a scalar into an array. 

Key Points:

  • ndarray.itemset function needs at least one argument.
  • The last argument you pass in the function is considered an “item“. 
  • arr.itemset(*args) is a quicker way to do same thing as arr[args] = item
  • The item should be a scalar value and args must select a single item in the array.

Syntax

numpy.ndarray.itemset(*args) 

Parameters:

  • *args : 
    • If one argument: a scalar, only used in case arr is of size 1. 
    • If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.

Examples

Let’s look at this example of the ndarray.itemset() method of the NumPy library.

Example 1:

Python3




import numpy as np
  
np.random.seed(345)
arr = np.random.randint(9, size =(3, 3))
print("Input array : ", arr)
  
arr.itemset(4, 0)
  
print ("Output array : ", arr)


Output :

Input array :  [[8 0 3]
[8 4 3]
[4 1 7]]
Output array : [[8 0 3]
[8 0 3]
[4 1 7]]

Example 2:

Python3




# Python program explaining 
# numpy.ndarray.itemset() function 
  
# importing numpy as geek 
import numpy as geek 
  
geek.random.seed(345
arr = geek.random.randint(9, size =(3, 3)) 
print("Input array : ", arr) 
arr.itemset((2, 2), 9
print ("Output array : ", arr) 


Output:

Input array :  [[8 0 3]
[8 4 3]
[4 1 7]]
Output array : [[8 0 3]
[8 4 3]
[4 1 9]]

Note: While the ndarray.itemset method is fast and efficient, but many people avoid it because this method can complicate the code and it might waste space if the array is not fully populated.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads