Working on Arrays
An Arrays stores a group of elements of same data types. In other words it stores either int data types or float data types.
An Array can increase or decrease its size dynamically. Python provides a Module whose name is array that helps to create an array and provides function related to it.
Creating an Array
An array can be created using below syntax:
Array name = array (type code, [elements])
Below are some list of type codes available:
- ‘b’ : Signed Integer
- ‘B’: Unsigned Integer
- ‘I’: signed Integer
- ‘I’: Unsigned Integer
- ‘f’: Floating point
- ‘u’: Unicode Integer
- a = array (‘I’, [2, 4, 6, 8])
- y = array (‘d’, [1.5, 2.2,-3.2, 5.75])
How to Import Array Module
There are three ways to import Array Module, Let’s discuss one by one:
Method1: Import entire array Module using import statement.
Now in this when we import the array module, an array class is available from that module, which is used to create an array.
A = array. Array (‘I’, [2, 4, 6, 8])
The first array is Module and second array represents the class name.
Method2: By using alias of array Module, we can create an array now.
Import array as arr
A = arr.array (‘I’, [2, 4, 6, 8])
Method3: By Importing all class, variables, and objects etc. from array module. This can be done by using *.
From array import *
A = array (‘I’, [2, 4, 6, 8])
Example1: Write a program to create Integer array.
Example2: Write a program to create an array of characters
How to create an array from another array
We can create an array from another array. Let’s have an example of array.
X1 = array (‘I’, [1, 2, 3, 4, 5])
Now when we want to create another array from X1 then we should write the following:
X2 = array (X1.typecode, (I for I in X1)
Now let’s understand the above example. Here X1.typecode gives the type code character of array X1. This type code is used for array X2.
Now I for I in X1: first I represents that its value is stored as elements in the array X2. This I value is got from ‘I’ in X1. In this all the elements in X1 will be stored in to X2.
Example 3: Write a program to create one array from another array.