Day 13 - Operating on Lists
Skills: None
Pre-reading: 5.1.4 (aside from 5.1.4.1), 5.1.6
Intro (20 mins)
- Last time we saw operations on lists of numbers from math and statistics. Today we are going to dive into many more built in operations on lists that come from lists.
- Imagine a list of discount codes used by a magazine:
discount-codes = [list: "NEWYEAR", "student", "NONE", "student", "VIP", "none"]
- Which may have come from a column of a table. As part of data cleaning, one
thing you might want to do first is figure out what are the distinct codes
used.
import lists as L
unique-codes = L.distinct(discount-codes) - We also have operations on lists that are similar to operations you saw
previously on tables. For example, we can
L.filter
to remove codes that represent no discount (in this case, normalized "none").fun is-real-code(code :: String) -> Boolean:
not(string-to-lower(code) == "none")
end
real-codes = L.filter(is-real-code, unique-codes) - Like how tables have
row-n()
, lists have a way of getting an element by position:first-code = real-codes.get(0)
- For tables, we had a few ways of transforming the existing data -- adding a
new column with
build-column
, or transforming a single column withtransform-column
. Since lists have only a single value, there is only one version, calledL.map
. - We can use this to, e.g., get lowercase versions of each discount code:
lower-codes = L.map(string-to-lower, codes-real)
Class Exercise (35 mins)
FIXME / TODO
Wrap-up (5 mins)
- Lists have many built-in operations -- we showed a few, but there are more at https://pyret.org/docs/latest/lists.html.