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'])

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

#creating an array from another array