Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
numpy.isscalar() in Python
Next article icon

numpy.isscalar() in Python

Last Updated : 02 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will elucidate the `numpy.isscalar()` function through a well-documented code example and comprehensive explanation.

Python numpy.isscalar() Syntax

Syntax : numpy.isscalar(element)

Parameters:

  • element: The input element to be checked for scalar properties.

Return Type:

  • bool: Returns True if the input element is a scalar, and False otherwise.

What is numpy.isscalar() in Python?

The `numpy.isscalar()` is a function in the NumPy library of Python that is used to determine whether a given input is a scalar or not. A scalar is a single value, as opposed to an array or a more complex data structure. The function returns `True` if the input is a scalar and `False` otherwise. It is a useful tool for type checking in numerical and scientific computing applications where distinguishing between scalar and non-scalar values is often necessary.

Python numpy.isscalar() Function Example

Here are several commonly used examples of the `numpy.isscalar()` function, which we will elucidate for better understanding.

  • Scalar Check in Python
  • Check if a Variable is a Scalar
  • Validating Input Type in a Function
  • Using isscalar() in Conditional Logic

Scalar Check in Python

In this example Python program uses NumPy's `isscalar()` function to check if an input array `[1, 3, 5, 4]` is a scalar and prints the result. It further demonstrates the function's use by checking the scalar status of an integer (`7`) and a list (`[7]`), providing output indicating whether each input is a scalar.

Python3
# Python program explaining # isscalar() function import numpy as np  # Input array in_array = [1, 3, 5, 4] print("Input array:", in_array)  # Check if the input array is a scalar isscalar_values = np.isscalar(in_array) print("\nIs scalar:", isscalar_values)  # Check if the input is a scalar (integer) print("\nisscalar(7):", np.isscalar(7))  # Check if the input (list) is a scalar print("\nisscalar([7]):", np.isscalar([7])) 

Output :

Input array :  [1, 3, 5, 4]
Is scalar : False
isscalar(7) : True
isscalar([7]) : False

Check if a Variable is a Scalar

In this example code uses NumPy's `isscalar()` to check if variables `x` (an integer) and `y` (a list) are scalars. It prints the results, indicating that `x` is a scalar (`True`) and `y` is not a scalar (`False`).

Python3
import numpy as np  x = 42 y = [1, 2, 3]  is_scalar_x = np.isscalar(x) is_scalar_y = np.isscalar(y)  print(f"x is a scalar: {is_scalar_x}") print(f"y is a scalar: {is_scalar_y}") 

Output:

x is a scalar: True
y is a scalar: False

Validating Input Type in a Function

In this example code defines a function `calculate_square` that takes a parameter `value`, checks if it is a scalar using `numpy.isscalar()`, and returns the square if it is. If the input is not a scalar, it raises a `ValueError`. It then calculates and prints the square of the scalar value 5, demonstrating the function's usage.

Python3
import numpy as np  def calculate_square(value):     if np.isscalar(value):         return value**2     else:         raise ValueError("Input must be a scalar")  result = calculate_square(5) print("Square of 5:", result) 

Output:

Square of 5: 25

Using isscalar() in Conditional Logic

In this example code defines a function `process_data` that checks if the input is a scalar or a NumPy array, printing the corresponding message. It's demonstrated with an integer (prints the value), a NumPy array (prints "Processing NumPy array data"), and a string (prints "Unsupported data type").

Python3
import numpy as np  def process_data(data):     if np.isscalar(data):         print("Processing scalar data:", data)     elif isinstance(data, np.ndarray):         print("Processing NumPy array data")     else:         print("Unsupported data type")  process_data(10) process_data(np.array([1, 2, 3])) process_data("Invalid") 

Output:

Processing scalar data: 10
Processing NumPy array data
Processing scalar data: Invalid

Next Article
numpy.isscalar() in Python

M

mohit gupta_omg :)
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python numpy-Logic Functions
Practice Tags :
  • python

Similar Reads

    numpy.isnan() in Python
    The numpy.isnan() function tests element-wise whether it is NaN or not and returns the result as a boolean array. Syntax :  numpy.isnan(array [, out]) Parameters :  array : [array_like]Input array or object whose elements, we need to test for infinity out : [ndarray, optional]Output array placed wit
    2 min read
    numpy.asscalar() in Python
    numpy.asscalar() function is used when we want to convert an array of size 1 to its scalar equivalent. Syntax : numpy.asscalar(arr) Parameters : arr : [ndarray] Input array of size 1. Return : Scalar representation of arr. The output data type is the same type returned by the input’s item method. Co
    1 min read
    numpy.isinf() in Python
    numpy.isinf() test element-wise whether a value is positive or negative infinity. It returns a Boolean array with True where the input is either +inf or -inf and False otherwise. Example:Pythonimport numpy as np a = np.array([1, np.inf, -np.inf, 0, np.nan]) res = np.isinf(a) print(res)Output[False T
    2 min read
    numpy.issubclass_() function – Python
    numpy.issubclass_() function is used to determine whether a class is a subclass of a second class. Syntax : numpy.issubclass_(arg1, arg2) Parameters : arg1 : [class] Input class. True is returned if arg1 is a subclass of arg2. arg2 : [class or tuple of classes] Input class. If a tuple of classes, Tr
    1 min read
    numpy.isposinf() in Python
    The numpy.isposinf() function tests element-wise whether it is positive infinity or not and returns the result as a boolean array.  Syntax :  numpy.isposinf(array, y = None) Parameters:   array : [array_like]Input array or object whose elements, we need to test for infinity. y : [array_like]A boolea
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences