Arrays Usage in Python

An index represents the position number of an element in an array. For example, when we create the following integer type array:

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.

indexing of python array

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.

A Python program to retrieve elements of an array using while loop.

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:

We can eliminate any one or any two in the items: 'start', 'stop' or 'stride' from the above syntax.

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.

A Python program to retrieve and display only a range of elements from an array using slicing.