Python – Create a Float Array

Create a Float Array in Python

In Python, you can create a float array using array() method of array module.

In this tutorial, you will learn how to create a Python array with floating point values in it, with examples.

To create a float array in Python, import array module, call array() method of array module, and pass the type code for float type as first argument and the list of elements for the initial values of array as second argument.

array(type_code, initial_values)

You can use any of the following type code to create an array with floating point numbers.

Type
Code
C
data type
Python
data type
Minimum
number of
bytes
'f'floatfloat4
'd'doublefloat8
Type code values to create integer array

Initial values (second argument) to the array() method is optional. If you do not pass any initial values, then an empty float array would be created.

1. Create a float array with initial values

In the following program, we create a float array my_array using array() method. Pass 'f' type code as first argument to the array() method, and pass a list of initial values to the array as second argument to the array() method.

Python Program

import array as arr

my_array = arr.array('f', [3.14, 5.60, 8.96])

print(my_array)
Run Code Copy

Output

array('f', [3.140000104904175, 5.599999904632568, 8.960000038146973])

2. Create an empty float array and add values

We can also create an empty float array, and then append floating point numbers to the array.

In the following program, we create an empty float array my_array, and then add some float values to this array.

Python Program

import array as arr

my_array = arr.array('f')
my_array.append(3.14)
my_array.append(5.60)
my_array.append(8.96)

print(my_array)
Run Code Copy

Output

array('f', [3.140000104904175, 5.599999904632568, 8.960000038146973])

3. Iterate over Float Array

We can use a For loop to iterate over the elements of given float array.

In the following program, we take a float array my_array, and then use a For loop to iterate over the floating point numbers in the array.

Python Program

import array as arr

my_array = arr.array('f', [3.14, 5.60, 8.96])

for element in my_array:
    print(element)
Run Code Copy

Output

3.140000104904175
5.599999904632568
8.960000038146973

Summary

In this Python Array tutorial, we learned how to create a float array in Python, using array() method of array module, with examples.

Related Tutorials

Code copied to clipboard successfully 👍