Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to create an array in Python

Onyejiaku Theophilus Chidalu

Overview

An array in Python is simply used to store multiple values or item of the same type together.

To create an array in Python we use the array() function after importing the array module. The array() function takes the following parameter values:

  • data_type: This parameter value specifies which data type of array we want to create. it could be an integer type, float type, signed long etc.
  • data_value: This parameter value contains the values of the array you are creating.

It is worthy to note that there are many data types and for that reason, some of them are listed in the table below:

Type code C type Python type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'i' signed int int 2
'I' unsigned int int 2
'f' float float 4
'b' double float 8

Example

Now, let’s create some simple arrays using the array() function.

# importing array from array creations
import array as arr

# to create an array of integer datatype i
a =  arr.array('i', [1, 2,  3, 4, 5, 6, 7 ])

# printing the newly created array
print('The integer datatype of array is: ', a)


# to create an arry in float datatype d
b = arr.array('d', [1.2, 2.5, 6.4, 5.1, 4.5])

# printing the float array
print('The float datatype of array is: ', b)
Creating an array in Python

Explanation

  • Line 2: We import the array module in python.
  • Line 5: We create an integer type of array variable a.
  • Line 8: We print the integer type of array variable, a, we created in line 5.
  • Line 12: We create a float type of array variable b.
  • Line 15: We print the float type of array variable, b, which we created in line 12.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring