Creating and Accessing Single-Dimension Arrays


Single-dimension arrays are actually a simple list of objects. One item appears after another in memory and you access the items using the numeric value that applies to that particular element. Singledimension arrays commonly appear in applications because many items fit within the list category. You can create arrays in a number of ways. For example, you can create a blank list using the following technique

[code]MyList = [][/code]

If you want to fill an array with data as part of the creation process, you can simply provide a list of values. For example, this code creates an array with four values.

[code]MyList = [1, 2, 3, 4][/code]

You’ve probably seen these techniques (or similar techniques) in other languages. However, IronPython has a few additional tricks up its sleeve. For example, you can fill an array with a sequence. The following code is perfectly acceptable and fills the array with the path variables.

[code]MyList = sys.path[/code]

In this case, the interpreter creates one array element for each path within sys.path. This approach makes it possible to access each path element individually. However, changing an array element won’t change sys.path. IronPython makes a copy of the content of sys.path and places it in MyList.

You can also use expressions to fill the array. This is an especially powerful technique because the expression can be any legal Python expression that produces a list of items as output. For example, the following code creates an array with the same list of path items in it, except this code relies on an expression to perform the task.

[code]MyList = list(‘Hello’)[/code]

In this case, MyList will contain one element for each letter. However, the expressions can become quite complex — as complex as you need them to generate the array elements. For example, the following code also works just fine.

[code]MyList = list(x*x for x in range(10))[/code]

This bit of code generates the squares of all of the numbers between 0 and 9 — range() begins with 0 and ends with 9 as output (see the “Using the range() Function” section of the chapter for more details). The expression need not work with just numeric data either. When you execute the following code

[code]MyList = list(x.upper() for x in “abc”)[/code]

MyList fills with the uppercase letters A, B, and C. Consequently, you can fill the array with the product of a method’s output. In fact, you can create your own functions to process the input from a list, as shown in Listing 4-4.

Listin g 4-4: Creating specialized array input


# Define a function to output values for the array.
def ArrayFill(x):
# Output a value that matches the input.
if x == ‘a’:
return ‘Red’
elif x == ‘b’:
return ‘Yellow’
elif x == ‘c’:
return ‘Blue’
return ‘Unknown’
# Create the list to process.
AString = ‘abcdABCD’
# Create the array.
MyList = list(ArrayFill(x.lower()) for x in AString)
# Print each array element.
for Output in MyList:
print Output
# Pause after the debug session.
raw_input(‘Press any key to continue…’)


The code begins by defining an array to create array elements. This function could be anything you choose. The point is that each call to the function provides a specific output based on the input: Red, Yellow, Blue, or Unknown.

The next step is to define the inputs, which appear in AString. Any sequence you want to process works fine.

Now the code creates the array using the complex expression shown in Listing 4-4. The expression loops through each value in AString and places it in x. The value in x is set to lowercase and passed to ArrayFill(), which then interprets the value and provides an output. Figure 4-4 shows the output from this example.

IronPython also includes some interesting array access features. For example, if you want to access every other array element, you use the code shown in Listing 4-5.

Listin g 4-5: Accessing specific array elements


# Create the array.
MyList = [1, 2, 3, 4, 5, 6]
# Access every other element.
for Output in MyList[::2]:
print Output


You can use complex expressions to create arrays.

The output is 1, 3, and 5 for this example. Actually, you can provide more than the step for the output. IronPython provides the means to provide start:stop:step with the colons. For example, if you wanted to start with element 1 instead of element 0, you’d type:

[code]for Output in MyList[1::2]:
print Output[/code]

This code outputs 2, 4, and 6 based on the previous input. You can control things even more. For example, look at the following code.

[code]for Output in MyList[1:4:2]:
print Output[/code]

Run this code and you’ll see 2 and 4 as output. The code begins with element 1, stops with element 4, and uses a step of 2.

Let’s look at one other interesting IronPython array technique. Listing 4-6 shows code that not only shows the array items, but also the index associated with that item.

Listin g 4-6: Looping through array elements


# Create the array.
MyList = [‘Zero’, ‘One’, ‘Two’, ‘Three’, ‘Four’]
# Display the items and their index.
for index, item in enumerate(MyList):
print index, item
# Pause after the debug session.
raw_input(‘Press any key to continue…’)


In this case, the code begins by creating an array with five strings in it. The for loop iterates through the array as normal. However, in this case, the example relies on the enumerate() function to obtain the index for the array elements. Consequently, the output consists of two values — the array index and the element value. You can read more about the enumerate() function in the “Using the enumerate() Function” section of the chapter. The output from this example appears in Figure 4-5.

Using functions enables you to extend the output of arrays.

By now you should have gotten the idea that arrays in IronPython are just a bit different from other languages in that they’re far more flexible and you can use them for a host of tasks.