## Notes
### Session 8
#### Immutable Objects
Earlier, we made a big deal about the fact that lists are mutable.
The reason this is important is because
certain objects are immutable – once created, their value cannot be changed.
Strings are a prime example of this. Although we treated strings the same
as primitives like integers and
booleans earlier, strings are actually objects.
Why did we do this? Think about this: if an object is immutable, it doesn't matter whether two variables
are pointing to the same string or two different strings with the same value! Thus, while strings are
actually immutable objects, we can treat them as we have before – as primitives. The only new meaning
this revelation has is that like lists, strings have member functions.
For strings (and tuples, when we get to them), it's easiest to think of them like primitives – directly
stored in the variable table.
---
### Day 6: Strings Revisited
Most of the member functions in lists modified the list and had no return value. Strings are immutable,
though – how do string member functions work? It turns out that member functions of
strings tend to
return a new string.
#### Program Text:
```python
message = "Hello"
print message
message.lower() # no effect
print message
message = message.lower()
print message
Output:
Hello
Hello
hello
Note: lower() is a function that converts a string into lowercase.
Here is a list of some useful string functions. Don't try to memorize these!
Even I don't remember them –
instead, when I need to look up a function, I go to the Python Quick Reference
website shown in class
(and on the website).
Page 2
A quick reminder before starting:
Remember that "A" and "a" are completely different characters! When writing functions that
manipulate strings, it's generally a good idea to deal with a single case (usually lowercase).
Functions that return a new string
str.capitalize() / str.lower() – Returns a copy of str with all letters converted to
uppercase/lowercase.
str.strip() – Returns a copy of str with all whitespace (spaces/tabs/newlines)
removed from the
beginning and end.
Example: " test ".strip() → "test"
str.replace(old, new) – Returns a copy of str with all instances of old replaced with new.
Example: "hallo all!".replace("al", "el") → "hello ell!"
Functions which return information about a string
str.count(substring) – Returns the number of times substring appears within str.
str.find(substring) / str.rfind(substring) – Returns the position of the
first/last instance of
substring within str.
s.startswith(substring) / str.endswith(substring) – Returns True if the string
starts/ends with
substring.
Example: "Hello".startswith("he") == False, but "Hello".endswith("lo") == True
Functions which transform the string into other types
str.split(separator) – Returns a list of words in str, using separator as the delimiter.
Example: "hello world, Mihir here".split(" ") → ["hello", "world,", "Mihir", "here"]
Example: "mississippi".split("s") → ["mi", "", "i", "", "ippi"]
separator.join(seq) – Takes a list of strings seq and combines them into a string.
Example: " ".join(["hello", "world"]) → "hello world"
Page 3
Day 4: Tuples
Tuples are the immutable counterpart of lists. Unlike a list, tuples cannot be changed.
Why/where are tuples useful?
Think of a tuple as multi-dimensional data. Just like you can store an integer
5 in a variable, you can
also store a two-dimensional coordinate (6,-3). You'll develop an instinct
for when to use tuples
versus lists as you continue in course 6 – just remember that it tends to be much
easier to use tuples
whenever you can get away with it.
Tuple Syntax:
(1,3,8) creates a tuple with elements 1, 3, 8.
Tuples are ordered: (1,3) != (3,1).
A singleton tuple (a tuple with one element) is created using (5,), not (5).
Example: (4,6) != [4,6] – One is a tuple, the other is a list.
You can convert between these formats using str(x), tuple(x), and list(x).
Day ?: Sequence Notation
Lists, strings, and tuples are all examples of sequences – a series of ordered items.
Common sequence operations:
Indexing: seq[i] returns the item at index i.
Length: len(seq) returns the length of a sequence.
Slicing: "hello"[0:3] == "hel".
Membership Operators: "ello" in "hello" == True.
Concatenation: "Yay! " * 5 repeats the string five times.
For Loops: Iterates through each element in a sequence.
Page 4
Day 7: Dictionaries
Dictionaries are mutable objects that store key-value pairs.
Important Notes:
Dictionaries are unordered – the order of entries does not matter.
Keys must be immutable (e.g., strings, tuples), but values can be any type (e.g., lists).
Dictionary Syntax:
{} creates an empty dictionary.
{"a": 5, "test": [1,2], 27: "Test"} creates a dictionary with three key-value pairs.
len(d) returns the number of entries in d.
Accessing/Modifying Entries:
example_dict = {"a": 5, "b": True}
print(example_dict["a"]) # prints 5
example_dict["a"] = 7 # updates value of "a"
del example_dict["a"] # removes key "a"
Key uniqueness: A dictionary cannot contain duplicate keys. Assigning
a new value to an existing
key overwrites the old value.
Dictionary Membership:
k in d returns True if key k exists in dictionary d.
Example: (27 in example_dict) == True
Example: (5 in example_dict) == False
Page 5
Day 7: Dictionary Member Functions
Some useful dictionary methods:
d.clear() – Removes all items from d.
d.copy() – Returns a copy of d.
d.pop(k) – Removes and returns the value associated with key k.
Day 7: For Loops and Dictionaries
Dictionaries can be iterated over using for loops, which iterate over keys by default.
Program Text:
example_dict = {"a": 5, "b": True}
for k in example_dict:
print(k, ";", example_dict[k])
Output:
a ; 5
b ; True
To mark this module as complete, you must finish this quiz. Once submitted, you'll need to wait 2 hours before attempting it again.