We start to write programs using a limited number of variables, but in real life, plenty of elements are required to be dealt with. For example, first we learn to write a program to find out the maximum between two variables. Then gradually we move to writing the same program for three, four or five variables. But if our task is to find the highest marks in a class of 60 students or more, then it will become a tedious job for us. This will mean 60 variables are to be declared to store marks of 60 students, so 60 input statements have to be used to input the marks of each student, and finally 60 if statements to find the maximum of these marks, and so on. Not only that, if another class contains less or more than 60 students, we cannot not use this program for that class. We have to rewrite the program according to that new class. Thus, this approach of processing a large set of data is too cumbersome and surely not flexible enough. Almost all modern high level programming languages provide a more convenient way of processing such collections. The solution is array or subscripted variables.
3.1 Definition
An array is a collection of homogeneous (i.e., same data type) data elements described by a single name and placed in contiguous memory locations. Each individual element of an array is referenced by a subscripted variable, formed by affixing to the array name with a subscript or index enclosed in brackets.
Thus, by declaring an array we can store a set of values, say 60 of a particular type, say, int, in a single variable without declaring 60 different variables of different names. All these values will be stored under a unique identifier (array name).
3.2 Creating an Array
In Python, we can create an array by importing the ‘array’ module. After importing we can declare an array as:
array(type_code, value_list)
Here,
value_list: specifies the list of elements which will be the content of the array.
type_code: specifies the data type of the elements which is going to be stored in the array. Table 3.1 shows commonly used type codes for declaring array.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.