In this post, we are going to learn about how to Declare an array in Python with examples. Python is a popular language that is used for Machine learning and data analytics and provides various data structures for data analytics and Manipulation. Python does not have an array as a built-in datatype instead the lists are used as an array in Python also known as a dynamic array. We often confuse Python list and array. The array is sequence type and the object stored in them are constraints.
Different ways to declare array in python
We will learn how to declare an array in python by using all three ways with examples.
- Using array Module
- Using List
- Using NumPy library
1. Declare array in Python using array Module
The Python array module is used to define an object of basic type string, int, characters, integer, or floating-point number. To use this module we have to import it into our program. The Python array module’s array() method takes two arguments, the first argument is data types format and the second argument is a list of values.
from array import *
array = array('i', [3,6,9,12])
for item in array:
print(item)
myarray = array('i', [])
print(array)
Output
array(i)
3
6
9
12
2. List to Declare array in Python
The Python list is a dynamic array and stores elements of different types whereas the array stores a collection of similar data elements in a contagious memory location. We can store elements of different data types in the list. In the below example we have first declared an empty array and declared an array of values of a different datatype.
#intialize empty array in python
myarr = []
print('python array:',myarr)
#Declare python array with values
myarr2 = ['C#',3,6,9,12,15]
print('Declare python array:\n',myarr2)
Output
python array: []
Declare python array:
['C#', 3, 6, 9, 12, 15]
3.NumPy module to Declare array in Python
The Numpy module is used to create and declare a NumPy array in Python. To use the NumPy module first we have to install and import it into our program. There are two NumPy functions that we can use to create a NumPy array.
- np.array(): create an array of given number and type of arguments
- np.arange(): The np.arange() specifies the range and type of data values and takes three arguments
- start: represent the first element of the array.
- stop: represent the last element of array
- step: The number of step intervals between array elements
Using np.array()
In this example, We have used np.array() to create and declare the NumPy array.
import numpy as np
myarr = np.array(['C#',10,20,30])
print(myarr)
Output
['C#' '10' '20' '30']
Using np.arange()
In this example, we have used np.np.arange() to create and declare the NumPy array.
import numpy as np
myarr = np.arange(3,15,3)
print(myarr)
Output
[ 3 6 9 12]
Summary
in this post, we have learned how to Declare an array in Python with examples by using three different ways Using array Module
Using List, Using NumPy library.