Convert list or NumPy array of single element to float

Learn, how to Convert list or NumPy array of single element to float in Python? By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a list or a numpy array with a single element and a function that can accept either a list or a numpy array and we need to return a float value from this function.

Converting a list or array of single element to float

For this purpose, we will Just access the first item of the list/array, using the index access and the index 0, this will be an int since that was what we inserted in the first place. If we want to convert it into a float, we can call the defined function where we can write a code to apply float() method on the item.

Convert array having single element to float

res = float(arr)

Convert array having single element to float (using index 0)

res = float(arr[0])

Let us understand with the help of an example,

Python program to convert list or NumPy array of single element to float

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([4])

# Display original array
print("Original Array:\n", arr, "\n")

# Converting to float
res = float(arr)

# Display result
print("Result:\n", res)

'''
# YOU CAN ALSO USE THIS...

# Converting to float (using index 0)
res = float(arr[0])

# Display result
print("Result:\n", res)
'''

Output

The output of the above program is:

Example: Convert list or NumPy array of single element to float

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.