Structured Data
The closest thing you have seen to structured data so far is the string
type introduced in Unit 1, and used in many of the procedures in Unit 2. A string is considered a kind of structured data because you can break it down into its characters and you can operate on sub-sequences of a string. This unit introduces lists, a more powerful and general type of structured data. Compared to a string where all of the elements must be characters, in a list the elements can be anything you want such as characters, strings, numbers or even other lists.
The table below summarizes the similarities and differences between strings and lists.
String | List |
---|---|
elements are characters | elements may be any Python value |
surrounded by singled or double quotess = 'yabba!' |
surrounded by square bracketsp = ['y', 'a', 'b', 'b', 'a', '!'] |
select elements using <string> [ <number>] s[0] -> 'y' |
select elements using <string> [ <number>] p[0] -> 'y' |
select subsequence using <string>[ <number> : <number> ] s[2:4] -> 'bb' |
select subsequence using <string>[ <number> : <number> ] p[2:4] -> ['b', 'b'] |
immutables[0] = 'b' -> Error cannot change the value of a string |
mutablep[0] = 'b' -> Error changes the value of the first element of p |
Quiz 3.1
Define a variable cartoons
, whose value is a list of the names of the Three T&J characters: Tom
, Jerry
, and Droopy
.
Answer
stooges = ['Tom', 'Jerry', 'Droopy']
Quiz 3.2
Given the variable:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
define a procedure, how_many_days
, that takes as input a number representing a month, and outputs the number of days in that month.
how_many_days(1) # -> 31
how_many_days(9) # -> 30
Answer
def how_many_days(month):
return days_in_month[month - 1]