Python - Access Array Items



Since the array object behaves very much like a sequence, you can perform indexing and slicing operation with it.

Example

import array as arr
a = arr.array('i', [1, 2, 3])
#indexing
print (a[1])
#slicing
print (a[1:])

Changing Array Items

You can assign value to an item in the array just as you assign a value to item in a list.

Example

import array as arr
a = arr.array('i', [1, 2, 3])
a[1] = 20
print (a[1])

Here, you will get "20" as the output. However, Python doesn't allow assigning value of any other type than the typecode used at the time of creating an array. The following assignment raises TypeError.

import array as arr
a = arr.array('i', [1, 2, 3])
# assignment
a[1] = 'A'

It will produce the following output

TypeError: 'str' object cannot be interpreted as an integer
Advertisements