Python creating arrays

We can call array() function of numpy module to create an array. When we create an array, we can specify the datatype of the elements either as 'int' or 'float'. We can create an integer type array as:

arr = array([10, 20, 30, 40, 50], int)

We can also eliminate 'int' in the above statement since Python can assess the datatypes of elements. To create an array with float type elements, we should specify 'float' as:

arr = array([1.5, 2.5, 3, 4, -5.1], float)

The same statement can be rewritten by eliminating 'float' as Python can judge the datatypes of the elements.

In the array, if Python interpreter finds one element belonging to 'float type', then it will convert all the other elements also into float type by adding a decimal point after the element as:

arr = array([10, 20, 30.1, 40])

If we display this array using print() function, we can see the array as:

[10. 20. 30.1 40. ]

To create an array with character type elements, we need not specify the datatype. We can simply write:

arr = array(['a', 'b', 'c', 'd'])

To create a string type array where can store a group of strings, we should use additional attribute 'dtype = str' in the array() function as:

arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], dtype=str)

Alternately, we can omit the 'dtype=str' in the above statement and write it as:

arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'])

Arrays creation examples:

A Python program to create a string type array using numpy.

CopiedCopy Code

from numpy import * 
arr = array(['Delhi', 'Hyderabad', 'Mumbai', 'Ahmedabad'], dtype=str) 
print(arr)

creating an array from another array

CopiedCopy Code

from numpy import * 
a = array([1,2,3,4,5]) 
b = array(a) #create b from a using array() function
c = a #create c by assigning a to c
print("a =", a)
print("b =", b)
print("c =", c)