15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using Sets 331<br />

Adding (and deleting) data in a set<br />

To add or delete data from a set, use the add and delete commands. In<br />

Python, the add command is add, and the delete command is remove.<br />

Every <strong>programming</strong> language uses slightly different names <strong>for</strong> the same command,<br />

so don’t worry about the particular command names used just as<br />

long as you understand the basic principles.<br />

To add more data to a set in Python, you have to identify the set name followed<br />

by the add command and the data you want to add. So if you had a<br />

set called clubmembers, you could use these commands:<br />

from sets import Set<br />

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

You could add a new name to that set by using the following command:<br />

clubmembers.add(‘Donna Volks’)<br />

To remove a name from a set, you have to identify the set name, use the<br />

remove command, and specify which data you want to remove, like this:<br />

clubmembers.remove(‘Bill Evans’)<br />

Figure 2-1 shows how add and remove commands change the contents<br />

of a set:<br />

Book III<br />

Chapter 2<br />

Bill Evans<br />

Bill Evans<br />

John Doe<br />

John Doe<br />

Mary Jacobs<br />

Mary Jacobs<br />

Donna Volks<br />

Original set<br />

Adding an item to a set<br />

just makes the set bigger.<br />

Sets and<br />

Linked Lists<br />

John Doe Mary Jacobs Donna Volks<br />

Removing an item from a set<br />

just makes the set smaller.<br />

Figure 2-1:<br />

Adding and<br />

removing<br />

data in a<br />

set is<br />

easier than<br />

adding and<br />

removing<br />

data in<br />

an array.<br />

0 1 2<br />

Bill Evans John Doe Mary Jacobs<br />

0 1 2<br />

John Doe Mary Jacobs<br />

Donna Volks<br />

If an array isn’t big enough,<br />

you can’t add any more<br />

data to it.<br />

Deleting data from an array<br />

leaves an empty space in<br />

that array.

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

Saved successfully!

Ooh no, something went wrong!