15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

332<br />

Using Sets<br />

✦ When you delete data from a set, the set is just one item smaller.<br />

✦ When you delete data from an array, you’re left with an empty space in<br />

the array.<br />

To remove all data in a set, most <strong>programming</strong> languages include a command<br />

that clears out an entire set. In Python, the command is clear, such as<br />

clubmembers.clear()<br />

Checking <strong>for</strong> membership<br />

If you store a bunch of names in an array, how could you verify whether a<br />

specific name is in that array? You’d have to examine each element in the<br />

array and compare it with the name you’re looking <strong>for</strong> until you either found<br />

a match or reached the end of the array. This typically requires a loop to<br />

examine every array element, one by one.<br />

Sets avoid this problem by making it easy to check whether a chunk of data<br />

is stored in a set. If you had a list of country club members stored in a set, it<br />

might look like this in Python:<br />

from sets import Set<br />

clubmembers = Set([‘Bill Evans’, ‘John Doe’, ‘Mary Jacobs’])<br />

To check whether a name is in a set (a member of that set), use a simple in<br />

command like this:<br />

‘John Doe’ in clubmembers<br />

If this command finds the name John Doe in the set defined by the<br />

clubmembers set, this would return a True value. If this command can’t<br />

find the name John Doe in the clubmembers set, this command would<br />

return a False value.<br />

From the computer’s point of view, it must still exhaustively compare every<br />

name in a set to see whether it matches the name you’re looking <strong>for</strong>, but<br />

from the programmer’s point of view, you can use a simple in command<br />

rather than write multiple lines of code to examine an array, element by element.<br />

The more work you can make the computer do, the less work you<br />

have to do.<br />

Another way to check <strong>for</strong> membership is to use the not command with the<br />

in command like this:<br />

‘Hugh Lake’ not in clubmembers

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!