9. Array Methods

As we discussed at the beginning of the last chapter, there are very few array methods for good reasons, and these all depend on the the implementation details. They're worth knowing, though:

itemsize()

The itemsize() method applied to an array returns the number of bytes used by any one of its elements.

>>> a = arange(10)

>>> a.itemsize()

4

>>> a = array([1.0])

>>> a.itemsize()

8

>>> a = array([1], Complex)

>>> a.itemsize()

16

iscontiguous()

Calling an array's iscontiguous() method returns true if the memory used by A is contiguous. A non-contiguous array can be converted to a contiguous one by the copy() method. This is useful for interfacing to C routines only, as far as I know.

>>> XXX example

typecode()

The `typecode()' method returns the typecode of the array it is applied to. While we've been talking about them as Float, Int, etc., they are represented internally as characters, so this is what you'll get:

>>> a = array([1,2,3])

>>> a.typecode()

'l'

>>> a = array([1], Complex)

>>> a.typecode()

'D'

byteswapped()

The byteswapped method performs a byte swapping operation on all the elements in the array.

>>> print a

[1 2 3]

>>> print a.byteswapped()

[16777216 33554432 50331648]

tostring()

The tostring method returns a string representation of the data portion of the array it is applied to.

>>> a = arange(65,100)

>>> print a.tostring()

A B C D E F G H I J K L M N O P Q R S T

U V W X Y Z [ \ ] ^ _ ` a b c

tolist()

Calling an array's tolist() method returns a hierarchical python list version of the same array:

>>> print a

[[65 66 67 68 69 70 71]

[72 73 74 75 76 77 78]

[79 80 81 82 83 84 85]

[86 87 88 89 90 91 92]

[93 94 95 96 97 98 99]]

>>> print a.tolist()

[[65, 66, 67, 68, 69, 70, 71], [72, 73, 74, 75, 76, 77, 78], [79, 80, 81, 82, 83, 84, 85], [86, 87, 88, 89, 90, 91, 92], [93, 94, 95, 96, 97, 98, 99]]

Go to Main Go to Previous Go to Next