Blograby

Using the enumerate() Function

Newer versions of Python and IronPython include the enumerate() function, which makes it easier to enumerate values in a sequence or array. Instead of using the range(len(MyList)) code, you can simplify things by using enumerate(MyList) instead. The output is two values: an index for the current element and the element value. Listing 4-11 shows the final version of the code for parsing a ragged array.

Listin g 4-11: Enumerating a ragged array

[code]

# Create a ragged array.
MyList = [[1, 2], 3, 4, [5, 6]]
# Display the array content.
print(‘Displaying the ragged array.’)
print(‘X Y Value’)
for x, value in enumerate(MyList):
if type(value).__name__ == ‘list’:
for y, subvalue in enumerate(value):
print x, y, ‘ ‘, subvalue
else:
print x, ‘N/A’, value
# Pause after the debug session.
raw_input(‘nPress any key to continue…’)

[/code]

The output of this code is the same as that shown in Figure 4-8, but the code itself is easier to understand than either example in the “Using the range() Function” section of the chapter. When you use the enumerate() function, you don’t have to calculate so many items — there’s less guesswork. Notice that the first for loop already has the index and associated value for the first array level. The inner loop performs less work to get the secondary array level as well.

The only negative about using enumerate() is the same negative associated with any new function — you won’t find it in older versions of Python or IronPython. Consequently, you could encounter compatibility issues when using this, or any, new function. Make sure you look at your platform before you use the enumerate() function in your code.

Exit mobile version