Python Array Usage
An index represents the position number of an element in an array. For example, when we create the following integer type array:
x = array('i', [10, 20, 30, 40, 50])
Python interpreter allocates 5 blocks of memory, each of 2 bytes size and stores the elements 10, 20, 30, 40 and 50 in these blocks.
Different ways of Array usage
To find out the number of elements in an array we can use the len() function as:
n = len(x)
The len(x) function returns the number of elements in the array 'x' into 'n'.
A Python program to retrieve the elements of an array using array index.
from array import *
x = array('i', [10, 20, 30, 40, 50])
n = len(x)
for i in range(n):
print(x[i], end=' ')
A Python program to retrieve elements of an array using while loop.
from array import *
x = array('i', [10, 20, 30, 40, 50])
n = len(x)
i=0
while i<n:
print(x[i], end='')
i+=1
A slice represents a piece of the array. When we perform 'slicing' operations on any array, we can retrieve a piece of the array that contains a group of elements. Whereas indexing is useful to retrieve element by element from the array, slicing is useful to retrieve a range of elements. The general format of a slice is:
arrayname[start:stop:stride]
We can eliminate any one or any two in the items: 'start', 'stop' or 'stride' from the above syntax.
arr[1:4]
The above slice gives elements starting from 1st to 3rd from the array 'arr'. Counting of the elements starts from 0. All the items 'start', 'stop' and 'stride' represent integer numbers either positive or negative. The item 'stride' represents step size excluding the starting element.
A Python program that helps to know the effects of slicing operations on an array.
y = x[1:4]
print(y)
y = x[0:]
print(y)
y = x[:4]
print(y)
y = x[-4:]
print(y)
y = x[-4: -1]
print(y)
y = x[0:7:2]
print(y)
A Python program to retrieve and display only a range of elements from an array using slicing.
from array import *
x = array('i', [10, 20, 30, 40, 50, 60, 70])
for i in x[2:5]:
print(i)