Topic 9: Arrays

A group of related variables with the same data type is referred to as an array . Variables in an array are stored in consecutive locations in the computer’s internal memory. Each variable in an array has the same name and data type.

You distinguish one variable in a one-dimensional array from another variable in the same array by using a unique integer, called a subscript. A subscript indicates a variable’s position in the array and is assigned by the computer when the array is created. The first variable in a one-dimensional array is assigned a subscript of 0, the second a subscript of 1, and so on.

Initializing Array

Syntax:
arrayName = [element1, element2, element3, elementn]
  • arrayName is the name of the array (same rules for naming an array as for naming a variable)
  • elements indicate the actual values in the array.
Example: Write a program with the following values in an array named num:10, 20, 30, 40.
  • num = [10, 20, 30, 40, 50]

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example
    1. for x in num:
    2. print(x)
Output
  • 10
    20
    30
    40
    50

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Table 9.1
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value/td>
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
len() returns the length of an array (the number of elements in an array).
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list