Topic 6: Lists, Sets, Tuples, Dictionaries: Recall: Stings
Topic 6: Lists, Sets, Tuples, Dictionaries: Recall: Stings
Recall: Stings
One way to think about a string is as a list/collection of characters:
name = "Smith College"
≈ ['S','m','i','t','h',' ','C','o','l','l','e','g','e']
0 1 2 3 4 5 6 7 8 9 10 11 12
if new_name in names:
print("They are in the class.")
else:
print("Hmm, I don't know them.")
Exercise: Friends
- Create a list of your friends and assign it to a new variable.
- Then depending on you user either print each name in ALL CAPS or lower case letters.
- If ALL CAPS, include an exclamation mark at the end (use a loop).
Answer: A TypeError
>>> animal = 'bat'
>>> animal[1] = 'd'
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
animal[1] = 'd'
TypeError: 'str' object does not support item assignment
Mutable vs. Immutable
- strings are immutable (which means we cannot change them in memory, we have to
overwrite them completely)
- lists defined with […] are mutable (which means we can change them in memory)
- if we want an immutable lists, we can define them with (…) instead, for example:
>>> animals = ('cat', 'dog', 'pig') #immutable
>>> animals[1]
'dog'
>>> animals[1] = 'bag'
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
animals[1] = 'bag'
TypeError: 'tuple' object does not support item assignment
List Operators
.append() - If you want to add a new item to the end of a list.
.insert() - If you want to add a new item into a list at a specific position.
.remove() - If you want to remove an item from a list, but if you try to remove an item that
isn’t in the list, the interpreter will throw a ValueError.
.copy() - If you want to copy the list.
For example:
>>> animals = ['cat', 'dog', 'pig', 'frog'] #mutable
>>> animals.append('turtle')
>>> animals.insert(3, 'fish')
>>> animals.remove('cat')
>>> print(animals)
['dog', 'pig', 'fish', 'frog', 'turtle']
>>> backup_animals = animals.copy()
>>> animals.remove('whale')
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
animals.remove('whale')
ValueError: list.remove(x): x not in list
- It is good practice to check if an element is in a list before removing it.
For example:
>>> animals = ['cat', 'dog', 'pig', 'frog', 'dog', 'pig']
>>> animals.count('dog')
2
>>> animals.reverse()
>>> print(animals)
['pig', 'dog', 'frog', 'pig', 'dog', 'cat']
>>> animals.sort()
>>> print(animals)
['cat', 'dog', 'dog', 'frog', 'pig', 'pig']
Answer:
friends = []
name = input("Enter a friend's name or DONE: ")
while(name != "DONE"):
friends.append(name)
friends.sort()
print(friends)
name = input("Enter a friend's name or DONE: ")
Next: Imagine we want to use the previous exercise to create a contact list. (see Dictionaries)
Lists of Lists
You can put a list inside a list.
For example, here is how I might store our cloths.
>>> cloths = [['top', 'blue', 'short sleeve'],
['top', 'red', 'graphic telephone'],
['bottom', 'blue', 'fashion jeans']]
>>> print(cloths)
[['top', 'blue', 'short sleeve'], ['top', 'red', 'graphic
telephone'], ['bottom', 'blue', 'fashion jeans']]
>>> print(cloths[1])
['top', 'red', 'graphic telephone']
>>> print(cloths[1][0])
top
>>> cloths.append(['dress', 'black', 'cocktail'])
>>> print(cloths)
[['top', 'blue', 'short sleeve'], ['top', 'red', 'graphic
telephone'], ['bottom', 'blue', 'fashion jeans'], ['dress', 'black',
'cocktail']]
Question: How are these dictionaries different that language dictionaries (in books or online)?
Dictionary Methods
.keys() - If you want to get a list of the keys in a dictionary.
.values() - If you want a list of the values in a dictionary.
.items() - If you want a list of the (key, value) pairs in a dictionary.
.pop() - If you want to remove an item from the dictionary.
.copy() - If you want to copy the dictionary (same as lists).
.zip() - Combine two lists into a dictionary.
For example...
#contacts is my dictionary made above
>>> print("Keys:", contacts.keys())
Keys: dict_keys(['Miranda', 'Kris', 'Jeffrey', 'Oliver', 'Leah', 'Fatima'])
>>> print("Values:", contacts.values())
Values: dict_values(['413-555-6472', '413-555-2349', '413-555-0204', '413-555-6193',
'413-555-9328', '413-555-0385'])
>>> for key, value in contacts.items():
print(key, value)
Miranda 413-555-6472
Kris 413-555-2349
Jeffrey 413-555-0204
Oliver 413-555-6193
Leah 413-555-9328
Fatima 413-555-0385
.zip()
If you want to combine two lists into one dictionary, use a comprehension and the zip(…)
function:
initial_names = ['Miranda', 'Kris', 'Fatima']
initial_numbers = ['413-555-6472', '413-555-2349', '413-555-0385']
contacts = {name:number for name, number in zip(initial_names,
initial_numbers)}
Recap
- strings: immutable ordered collections of characters
- lists: mutable ordered collections of objects
- dictionaries: mutable unordered collections of objects
def main():
contacts = dictionaryOperations()
new_contacts = modifyFriends(contacts)
print()
print(contacts)
print(new_contacts)
This results in contacts and new_contacts being the same.
Exercise: Course Dictionary Con't
Add to the program you wrote above, to allow for changes during the add/drop period.
Loop until the user enters 'DONE' and allow for additions and removals from your course
dictionary.
Learning Reflection
Take 3-5 minutes,