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.

330<br />

Using Sets<br />

2. Assign each variable with a different name like this:<br />

Day(0) = “Monday”<br />

Day(1) = “Tuesday”<br />

Day(2) = “Wednesday”<br />

Day(3) = “Thursday”<br />

Day(4) = “Friday”<br />

Day(5) = “Saturday”<br />

Day(6) = “Sunday”<br />

This would store all the days of the week inside a single array variable,<br />

although it requires multiple lines to store data in each array element.<br />

However, there’s a simpler way to lump related data together — use a data<br />

structure called a set. Like an array, a set groups data in a single variable<br />

name, but a set has several advantages:<br />

✦ You don’t have to define a fixed size ahead of time.<br />

✦ You don’t have to identify each chunk of data with an index number.<br />

✦ Sets can store a mixed variety of data types, such as Integers and<br />

Strings. (An array can only hold a single data type.)<br />

Defining a set lists all the data you want to store, as shown in this Python<br />

<strong>programming</strong> language example:<br />

from sets import Set<br />

days = Set([‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,<br />

‘Friday’, ‘Saturday’, ‘Sunday’])<br />

Certain features aren’t always a built-in part of a <strong>programming</strong> language,<br />

such as sets in Python. Rather than create a complicated language with lots<br />

of built-in features that not everyone will ever use, many <strong>programming</strong> languages<br />

add additional features through libraries, which are separate subprograms.<br />

For example, the Pascal language includes sets as a built-in data<br />

structure but the Python language does not. To use sets in Python, you must<br />

include (or import) a separate library that lets you use sets in a program. To<br />

use sets in Python, you must use the Python library called (surprise!) Set.<br />

In this Python language example, the variable days contains the entire set or<br />

group of the days defined by the Set command. To print the contents of this<br />

set, you can use a print command followed by the name of the set like this:<br />

print days<br />

This command would print:<br />

Set([‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’,<br />

‘Saturday’, ‘Sunday’])

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

Saved successfully!

Ooh no, something went wrong!