Blograby

Working with the Collections Module

Collections are another in a series of containers that you can use to store information in memory. For IronPython developers, the main reasons to use collections are:

IronPython doesn’t include collection support by default; you must import it into your application through the collections module. The collections module comes with a number of collection objects. If you’re using the latest version of IronPython, you gain access to these collection features:

For the most part, collections really are just replacements for the default IronPython storage containers such as list. In many cases, you see collections used to support specialized storage

classes — something not discussed in this chapter. To give you an example of how the objects in the containers module work, this section discusses the deque, which has the following methods associated with it.

Now that you have a basic idea of what a deque can do, it’s time to take a look at one in action. Listing 4-12 shows a basic deque example.

Listin g 4-12: Interacting with a deque

[code]

# Define a function for printing.
def Show(type, array):
print type
for String in array:
print String
# Import just the deque feature of the collections module.
from collections import deque
# Create the deque.
Numbers = deque([‘Red’, ‘Yellow’, ‘Blue’])
Show(‘Original Deque’, Numbers)
# Add a value to the deque.
Numbers.append(‘Orange’)
Show(‘nAppend Orange to the Right’, Numbers)
# Add a value to the left side of the deque.
Numbers.appendleft(‘Green’)
Show(‘nAppend Green to the Left’, Numbers)
# Remove a value.
Numbers.remove(‘Yellow’)
Show(‘nRemoved Yellow’, Numbers)
# Pop a value.
Popped = Numbers.pop()
print ‘nPopped:’, Popped
# Rotate the deque.
Numbers.rotate(2)
Show(‘nRotated 2 to the Right’, Numbers)
# Pause after the debug session.
raw_input(‘Press any key to continue…’)

[/code]

This example begins with a slightly modified version of the Show() function provided in Listing 4-7. Essentially, using this function saves a little of the coding time the developer requires to display the output onscreen.

A deque is more flexible than the built-in structures because you can work with both the right and left side of the deque. In this case, the code appends a value to the right and then to the left.

As with the built-in structures, you can remove, delete, or pop values from the deque. Unlike the built-in structures, you can also pop values from the left, which means you can create a number of interesting structure types. For example, you could create a rotating queue. Of course, you don’t even have to worry about popping values if you want to rotate values — simply use rotate() as shown in the example.

 

Exit mobile version