Skip to main content

Section 2.2 Collections of Data

Preview Activity 2.2.1.

(a)

Use code cells to find the squares of the counting numbers from \(0\) to \(9\text{:}\) \(0^2=0\text{,}\) \(1^2=1\text{,}\) \(2^2=4\text{,}\) \(\cdots\text{.}\) (Remember that ** is used in Python to denote an exponent.)

(b)

The sum of the cubes of \(0\) through \(4\) may be found by running 0**3+1**3+2**3+3**3+4**3, which turns out to be \(100\text{.}\)

Show that the sum of the squares of \(0\) through \(9\) is equal to \(285\text{.}\)

(c)

To avoid a lot of repetition, we may quickly produce the cubes of \(0\) through \(4\) as a list by running cubes = [n**3 for n in range(5)]. Then sum(cubes) also results in \(100\text{.}\)

Adapt this technique to show that the sum of the squares of \(0\) through \(99\) is equal to \(328{,}350\text{.}\)

Activity 2.2.2.

An unordered collection of mathematical objects is known as a set. Sets are written as a pair of curly braces surrounding a description of its members, such as \(\{2,8,1,4\}\text{.}\)

(a)

Sets may be declared in Python and SageMath using the syntax {2,8,1,4}. Use this syntax and the equality operator == to confirm that \(\{100,101,100\}\text{,}\) \(\{101,100\}\text{,}\) and \(\{100,101\}\) are all the same set (since they all contain exactly the same numbers).

(b)

The union of many sets describes anything that belongs to any of the given sets. For example, the union of \(\{1,2,3\}\) with \(\{3,4,5\}\) may be found using the code {1,2,3} | {3,4,5}, resulting in \(\{1,2,3,4,5\}\text{.}\)

Find the union of the three sets \(\{1,2,4,7\}\text{,}\) \(\{2,5,7,9\}\text{,}\) and \(\{0,2,3,7\}\text{.}\)

(c)

The intersection of many sets describes only the things that belong to all of the given sets. For example, the intersection of \(\{1,2,3\}\) with \(\{3,4,5\}\) may be found using the code {1,2,3} & {3,4,5}, resulting in \(\{3\}\text{.}\)

Find the intersection of the three sets \(\{1,2,4,7\}\text{,}\) \(\{2,5,7,9\}\text{,}\) and \(\{0,2,3,7\}\text{.}\)

(d)

Sets may contain other kinds of data, such as strings.

Find the union and intersection of the sets {1,2,3} and {1,"2","three"}.

Activity 2.2.3.

Sets are useful collections when you only care if a datum belongs to the set or not. But often you want your data to be ordered, and often you want to be able count the same datum multiple times in your collection. This is where lists are useful.

(a)

Lists use hard brackets [2,8,1,4] instead of curly brackets. Use == to verify that each of the lists [100,101,100], [101,100], and [100,101] are not considered equal to each other, since even though they contain the same data, it appears in different orders and frequencies.

(b)

The concatentation of many lists attaches them in order from end-to-end. For example, the concatenation of [1,2,3] with [3,4,5] may be found using the code [1,2,3] + [3,4,5], resulting in [1,2,3,3,4,5]. (Note that 3 is repeated since lists allow repeats.)

Find the concatenation of the three lists \([1,2,4,7]\text{,}\) \([2,5,7,9]\text{,}\) and \([0,2,3,7]\text{.}\)

(c)

Like sets, lists may contain data besides raw numbers, such as strings.

Find the concatenation of the lists [1,2,3] and [1,"2","three"].

(d)

Elements of a list can be changed as shown in 2.2.1.

favorite_numbers = [1,"two",7,3.14]
# Characters after the hashtag sign are comments and don't affect code.
# Python indexes with counting nunmbers, starting with 0 (known as 0-indexing).
favorite_numbers[0] = "One."  # changes the initial element 1 to "One."
favorite_numbers[2] = 42      # changes the element 7 to 42
print(favorite_numbers)       # outputs ['One.', 'two', 42, 3.14]
Listing 2.2.1. Changing elements of a list.

Let favorite_things = ["raindrops", "roses", "whiskers", "kittens"], and then use the techniques from 2.2.1 to change “roses” and “kittens” into some of your favorite things (leaving "raindrops" and "whiskers" in place).

(e)

Tuples are similar to lists in that they store ordered collections of data, but are used in different contexts. An important difference is that their elements are fixed. (That is, lists are mutable while tuples are immutable.)

Copy 2.2.2 to a Code cell, and replace the two indicated comments appropriately.

triple_list = ["one", "two", "three"]
triple_tuple = ("one", "two", "three")

# Attempts indented block of code that may cause an error
try:
    print("Trying to change 'two' to 2 in the list.")
    # REPLACE this line to change triple_list appropriately
# Handles possible error
except TypeError:
    print("This should never appear since list elements can be replaced.")

# Attempts indented block of code that may cause an error
try:
    print("Trying to change 'three' to 3 in the tuple.")
    # REPLACE this line to try to change triple_list appropriately
# Handles possible error
except TypeError:
    print("This should appear since tuple elements cannot be replaced.")

print(triple_list, triple_tuple) # outputs ['one', 2, 'three'] ('one', 'two', 'three')
Listing 2.2.2. Trying to alter a tuple.

Activity 2.2.4.

Lists are useful for organizing multiple values of data, but there's no great way to assign labels to each element in the list. Dictionaries are used to mitigate this.

(a)

The dictionary student_dict = {"name": "Jessica", "age": 19, "favorite_teacher": "Dr. Clontz"} represents the student data given in 2.2.3 as keys and values.

Table 2.2.3. Data stored in student_dict.
Key Value
"name" "Jessica"
"age" 19
"favorite_teacher" "Dr. Clontz"

Create a dictionary with the same keys for someone in your group.

(b)

Values stored in a dictionary can be easy retrieved by looking them up by key. For example, student_dict["favorite_teacher"] equals "Dr. Clontz", and print(f"{student_dict['name']} is {student_dict['age']} years old.") outputs Jessica is 19 years old.. (Note the switching of single and double quotes.)

Create a code cell that outputs a sentence similar to the following, using the dictionary you created in the previous task.

[Student name]'s favorite teacher is [teacher name].

Activity 2.2.5.

To avoid repetition, ranges and comprehension may be used to quickly describe longer lists, sets, and dictionaries.

(a)

Using the range() tool, we can quickly create lists of counting numbers. For example, list(range(10)) returns the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Note that this list contains ten different elements, but doesn't contain the number 10 itself.

By providing two numbers, you can specify the starting number (included) and ending number (not included). For example, list(range(-5,5)) == [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4].

Use a range to create the list [-10, -9, ..., 9, 10].

(b)

Comprehension allows us to use formulas when defining a list. For example, [2*n for n in range(10)] == [0, 2, 4, ..., 18].

Use comprehension to square each of the numbers in the list [-10, -9, ..., 9, 10], producing [100, 81, ..., 81, 100].

(c)

Comprehension can also be used with sets and dictionaries. For example, {f"{n} doubled": 2*n for n in range(10)} creates the dictionary {'0 doubled': 0, '1 doubled' 2, ..., '9 doubled': 18}.

Use comprehension to create the dictionary {'-10 squared': 100, '-9 squared': 81, ..., '10 squared': 100}.

Exercises Exercises

1.

Create a set with all the multiples of three between \(0\) and \(20\text{:}\) \(\{0,3,\cdots,18\}\text{.}\)

2.

Create a set with all the multiples of four between \(0\) and \(20\text{:}\) \(\{0,4,\cdots,20\}\text{.}\)

3.

Find the intersection and union of the sets in the previous two exercises.

4.

Create a list with words beginning with the letters “A” through “J”, such as ["apple", "banana", ..., "jump"]. Save it to a CS variable named alphabet_words.

5.

Concatentate your alphabet_words with the list ["kangaroo", "limbo", "mango"].

6.

Replace your word beginning with “F” in alphabet_words with the word “zebra”, leaving the others as-is.

7.

Create a dictionary with the data in the following table, and save it as the CS variable player_data.

Key Value
"id" 1234
"username" "Hunter12"
"score" 567
"joined_on" "2020-07-23"

8.

Add 100 points to player_data's score.

9.

Use player_data to print out a sentence using the following format.

Player [user name] signed up on [date] and has earned [X] points.

10.

Use comprehension to create the list ['1+1=2', '2+2=4', ..., '100+100=200'].