LPTHW Exercises 35 - 39
(12/5/13 -- 6:30pm PST)
LISTS, TUPLES, and Dictionaries
Review
- Boolean Expressions
- IF/ELSE Statements
- Lists
- For Loops
- While Loops
- List Indexing
Exercise 36:Debugging
- Write small chunks of code and then run it
- Use print statements to figure out state and flow
- pdb.set_trace()
Exercise 37: Symbol review
Seriously, make sure
that you do this exercise on your own!
Exercise 38: List Operations
Lists are data types or values in Python
They have built-in functions to perform actions such as:
sort (e.g. smallest to largest)
append (add item to end)
insert (add item somewhere else)
convert to string
Extra info: List Mutability
Integers, Strings, and Booleans are immutable
This means that their value can't be changed
To update variables, values must be reassigned
a = "Some random string"
a[0] = "z" ### This will fail because strings can't be changed
a = "z" + a[1:] ### we must create a new string and re-assign to a
Lists, on the other hand, are mutable
Can be changed (items added, removed, changed, etc)
sort, append, remove, etc all change the actual list
Extra Info: Tuples
A very similar data type to Lists
A tuple is an ordered sequence of items
Instead of brackets, tuples are created with parentheses
We've seen tuples before with string interpolation
"This is %s an example of %s" % ("good", "tuples")
my_sample_tuple = (1, "sample", 4, 9)
Difference with lists is that tuples are IMMUTABLE
Exercise 39: Dictionaries
Dictionaries are similar to Lists
They are mutable
Assignment and indexing is similar
They are NOT ordered
Instead they are lookup tables with keys and values
Each key is associated with a value
With the key, you "look up" that value
Exercise 39 Continued
chores = {"Monday": "rake yard", "Tuesday": "dentist appointment"}
print chores["Monday"]
# dictionaries have built-in functions, just like Lists
print chores.keys()
print chores.items()
for day, assignment in chores.items():
print "On %s, I will %s" % (day, assignment)
chores["Wednesday"] = "wash clothing"
print chores
thursday_chore = chores.get("Thursday", "I have nothing planned")
print thursday_chore
LPTHW Exercises 35 - 39 (12/5/13 -- 6:30pm PST)
By benjaminplesser
LPTHW Exercises 35 - 39 (12/5/13 -- 6:30pm PST)
- 1,320