Typed Arrays in IronPython

From IronPython Cookbook

Being a 'staticy' type of platform, the .NET arrays are typed. Of course IronPython doesn't need any of this, nor any generics conflucation, because the native list type is as generic as you are ever going to need.

However, if (and when) you communicate with the .NET framework, you may need to create a typed array, or receive one back.

Creating typed arrays from IronPython is easy:

from System import Array

intArray = Array[int](range(10))
# intArray is now an integer array, containing the numbers 0-9

strArray = Array[str](['hello', 'world'])
# strArray is now a string collection containing 'hello' and 'world'

.NET arrays can be indexed and iterated over as if they were Python lists:

hello = strArray[0]
strArray[0] = 'Goodbye'
for entry in strArray:
   print entry

You can also check for membership using 'in' and test their length with 'len'. One important difference (other than that you must honour their type), is that in Python an empty array will be 'False' in the boolean sense. This isn't true of a .NET array.

Turning a .NET array into a Python list is trivially easy:

strList = list(strArray)

There is an alternative way of creating arrays, without pre-populating with data:

import System

intArray = Array.CreateInstance(int, 100)
byteArray = Array.CreateInstance(System.Byte, 2048)

Multidimensional arrays

There are two ways of creating multidimensional Arrays. You can create an array of arrays:

array = Array[Array[int]]( ( (1,2), (3,4) ) )

Doesn't look very nice, but lets you populate Array on creation. Extracting values from such arrays is a bit ugly:

value = array[0][1]

The other (clearer) way to create multidimensional arrays is to use Array.CreateInstance passing type as a first argument followed by dimension sizes.

array = Array.CreateInstance(int, 2, 3)
cube = Array.CreateInstance(int, 3, 3, 3)

The first line will create a 2x3 array. The second will create a 3x3x3 cube. You can refer to multidinemsional array values using comma notation:

value1 = array[1, 2]
value2 = cube[0, 1, 2]


Array Methods

Array has a range of methods available.

array = Array[int]((1, 2, 3, 4))

Array.Reverse(array)
Array.Sort(array)

new_array = Array.Copy(array)


Back to Contents.

TOOLBOX
LANGUAGES