Skip to content
Snippets Groups Projects
Commit 5c5a8cf6 authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

lec 14 lists

parent e642cfb1
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 1: Try to mutate a string
name = "Plate"
# Change the entire string to be uppercase
# Change only last letter of name to "o" so that name = "Plato"
print(name)
# Takeaway:
```
%% Cell type:code id: tags:
``` python
# Warmup 2: practice using find and in
secret_word = "raspy"
# find the index of p'
print(secret_word.find(???))
# find the index of 'e'
print(secret_word.find(???))
# now try to use the "in" keyword
# what's the difference?
# find if 'p' is in our secret string using the 'in' keyword
print(??? in secret_word)
# find if 'e' is in our secret string using the 'in' keyword
print(??? in secret_word)
```
%% Cell type:markdown id: tags:
# Lists
## Readings
- [Downey Ch 10](https://greenteapress.com/thinkpython2/html/thinkpython2011.html)
- [Python for Everybody, Ch. 9](https://runestone.academy/ns/books/published/py4e-int/lists/toctree.html)
## Learning Objectives
After this lecture you will be able to...
- Create a list and use sequence operations on a list.
- Write loops that process lists
- Explain key differences between strings and lists: type flexibility, mutability
- Mutate a list using
- indexing and double indexing,
- methods such as append, extend, sort, and pop
- split() a string into a list
- join() list elements into a string
%% Cell type:markdown id: tags:
### Creating Lists
A **list** is used to store multiple items into a single data structure. To create a list you use square brackets `[]`.
**Be Careful** -- notice that <u>square brackets now have two meanings</u> in Python. They are used for indexing and slicing (i.e. accessing the items within a sequence) and they are use for creating. Let's see the difference:
**Indexing and Slicing:**
```python
name = 'rumplestiltskin'
last_part = name[-4:] # <----slicing the value 'skin'
first_ch = name[0] # <----indexing the value 'r'
```
**Creating a List:**
```python
nothing = [] # <-- creating an empty list
greetings = ['hello','hola','dag','Kon\'nichiwa'] # <-- creating a list of 4 strings
primes = [23,27,29] # <-- creating a list of 3 integers
rand_items = ['flugelhorn',23.17, True, 973] # <-- creating a list of 4 items (mixed types)
```
Do you see the difference? If the square brackets *come right after a sequence* then you are accessing an item or items in the sequence. If the square brackets *stand alone* then you are creating a list.
%% Cell type:code id: tags:
``` python
# A list is a sequence seperated by commas
# add one more thing to your grocery_list
grocery_list = ["bread", "milk", "eggs", "apples", "macNcheese"]
print(grocery_list, len(grocery_list), sep='\t')
```
%% Cell type:markdown id: tags:
A list is a sequence so you can use all of the sequencing techniques you used with strings when you are working with lists. Namely, you can use the `len()` function, indexing, slicing, and `for` loops to work with the items in a list.
### You Try It
Change the code in the cell below to access the elements of the `grocery_list`. The `in` operator can be used with sequences. It returns `True` if the element is in the sequence, otherwise it returns `False`.
%% Cell type:code id: tags:
``` python
# Sequence Operations: indexing, slicing
print(grocery_list, len(grocery_list), sep='\t')
# TODO: print the 2nd item in grocery _list
print(grocery_list)
# TODO: print the last item in grocery_list
print(grocery_list)
# TODO: slice to get the eggs and apples
print(grocery_list)
## TODO: finish the for loop to print out every item in the list
for ??? in ???:
pass
```
%% Cell type:code id: tags:
``` python
# the 'in' operator can be applied to a list
favorite_numbers = [4, 7, 14, 17, 84]
print(7 in favorite_numbers)
# make a false statement
print()
```
%% Cell type:code id: tags:
``` python
# Why does the following give an IndexError?
# print(grocery_list[len(grocery_list)])
# Put Answer Here:
```
%% Cell type:markdown id: tags:
You can use the `+` operator to concatenate lists together and the `*` operator to repeat the elements in a list.
%% Cell type:code id: tags:
``` python
# Lists can be concatented with +
both = [10, 20, 30] + [13, 4, 9, 8]
print(both)
```
%% Cell type:code id: tags:
``` python
# Lists can be repeated with *
triple = ["LET'S", "GO", "RED"] * 3
print(triple)
```
%% Cell type:markdown id: tags:
### Write loops that process lists
the `for` loop is an excellent way to walk over every element of a list. Finish each of the following loops.
%% Cell type:code id: tags:
``` python
# count how many words have length > 5 in grocery_list
grocery_list = ["butter", "milk", "eggs", "apples", "macNcheese"]
count = 0
for word in grocery_list:
pass
print(count)
```
%% Cell type:code id: tags:
``` python
def longest_word(word_list):
'''Given a list of strings, return the string with the longest length.
If more than one, return the first occurrence.'''
max_length = 0
longest_word = None
for i in range(len(word_list)):
# TODO find the longest word
pass
return longest_word
print(grocery_list)
print(longest_word(grocery_list))
#print(longest_word(['aaaa', 'xzy', 'hello']))
# TODO: What if we wanted to print the last occurence?
#print(longest_word(['aaaa', 'xzy', 'hello', 'world']))
```
%% Cell type:code id: tags:
``` python
# TODO Get a list of all engineering majors in your lecture
# Use the `find()` method to see if 'Engineering' is part of the primary major
# and use `in` to see if that major is not already in the list
import project
engineering_major_list = []
for idx in range(project.count()):
major = project.get_primary_major(idx)
pass
print(engineering_major_list)
```
%% Cell type:markdown id: tags:
![str%20list%20venn.png](attachment:str%20list%20venn.png)
%% Cell type:markdown id: tags:
### Explain key differences between strings and lists: type flexibility, mutability
There are two main differences between strings and lists: mutability and flexible types:
- **Lists can hold all types while strings cannot.**
A string can only hold characters while a list can hold any data type:
```python
mylist2 = [-7, 3.14, True, "Frog", [7,1]]
```
- **Lists can be mutated while strings cannot.**
You can change what is held at a particular position within a list. You do this using indexing:
```python
mylist = [1,2,3,4]
mylist[0] = 7
print(mylist)
```
```
[7,2,3,4]
```
Notice how the element at index 0 is assigned the value 7. The old value (1) is disgarded and the new value replaces it. You cannot do this with strings.
%% Cell type:markdown id: tags:
### You Try It
Finish the code below to explore looking at the types inside a list (even inside a list that is inside a list).
%% Cell type:code id: tags:
``` python
# Difference 1: a string only holds characters, a list can hold anything
list3 = ["hello", 14, True, 5.678, ["list", "inside", "a", "list"]]
# TODO: fix the bug in this loop
for i in (len(list3)):
# TODO: add to the print statement to print the type of the current item as well.
print(i, list3[i])
print()
```
%% Cell type:code id: tags:
``` python
# TODO: print out the last thing in list3
# TODO: print out the word "inside" using double indexing
# TODO: print out the type of the last thing in list3
```
%% Cell type:code id: tags:
``` python
# A list of lists!
game_grid = [
[".", ".", ".", ".", ".", "S"],
[".", "S", "S", "S", ".", "S"],
[".", ".", ".", ".", ".", "S"],
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", "S", "."],
[".", ".", ".", ".", "S", "."]
]
for row in game_grid:
for position in row:
print(position, end = "")
print()
```
%% Cell type:code id: tags:
``` python
# Difference 2: a string is immutable....
name = "Miles"
#Question: which of the following two lines will cause Runtime error?
name = "Andrew"
name[-1] = "a"
print(name)
```
%% Cell type:markdown id: tags:
### Mutate a list using indexing and double indexing,
%% Cell type:code id: tags:
``` python
# ... but the elements of a list are mutable
list3 = ["hello", 14, True, 5.678, ["list", "inside", "a", "list"]]
# change 14 to your favorite number
# change "a" to "another"
print(list3)
```
%% Cell type:markdown id: tags:
### Mutate a list using methods such as append, extend, pop, and sort
Just like there are methods for working with strings, Lists also have methods that are commonly used with them:
| List Methods | Purpose |
|---|---|
| `append()` | Add an item to the end of the list |
| `extend()` | Add all items from another list |
| `pop()` | retrieve and remove item from list |
| `remove()` | remove first matching item from list, error if nothing matches |
| `sort()` | sort the elements of list using natural ordering |
%% Cell type:code id: tags:
``` python
# append adds onto the end
new_groc_list = ['peanut butter', 'bread', 'jelly']
new_groc_list.append("nutella")
# add something else onto the end
print(new_groc_list)
```
%% Cell type:code id: tags:
``` python
# extend adds the elements of a list, one at a time, to the end of another list
new_groc_list.extend(['cheese', 'pickle'])
new_groc_list
```
%% Cell type:code id: tags:
``` python
# pop removes by index
# pop 'bread'
item = new_groc_list.pop(1)
print(item)
print(new_groc_list)
# the default value of pop is -1
# remove the last item
item2 = new_groc_list.pop()
print(item2)
print(new_groc_list)
```
%% Cell type:code id: tags:
``` python
# remove removes by matching value
# remove 'nutella'
new_groc_list.remove('nutella') # Note that remove() returns None
print(new_groc_list)
new_groc_list.remove('milk')
```
%% Cell type:code id: tags:
``` python
# sort reorders the elements in a list by their natural ordering
nums = [45, 13, 87, 23, 97, 44, 50, 7]
nums.sort() # sort by natural ordering
print(nums)
print(len(nums), len(nums) // 2) # print the length of nums
# print out the median value:
if len(nums) % 2 == 0:
print((nums[len(nums) // 2 - 1] + nums[len(nums) // 2]) / 2)
else:
pass # TODO: just get the middle number
```
%% Cell type:markdown id: tags:
### split() a string into a list
%% Cell type:code id: tags:
``` python
# split turns a string into a list based on a string to split off of
# https://www.w3schools.com/python/ref_string_split.asp
groceries_input = input("Enter your grocery list: ")
groceries = groceries_input.split(",")
print(groceries)
if not 'nutella' in groceries:
print('Don\'t forget the nutella!')
```
%% Cell type:code id: tags:
``` python
# join turns a list into a single string
print(grocery_list)
print(" ".join(grocery_list))
```
%% Cell type:markdown id: tags:
### You Try It
Use the string and list methods to finish the programs in the cells below.
%% Cell type:code id: tags:
``` python
# Write a program that manages a grocery list!
# A: Add an item. Ask the user to add an item to their list.
# D: Delete an item. Ask the user what to remove from their list.
# P: Print the grocery list.
# Q: Quit.
my_groceries = []
while True:
choice = input("What do you want to do? (A, D, P, Q): ")
# TODO_0: There's a bug... Fix this.
choice.upper()
if choice == 'A':
# TODO_3: Prompt the user to enter in a food and add it to the list.
pass
elif choice == 'D':
# TODO_4: Prompt the user to enter in a food and remove it from the list.
pass
elif choice == 'P':
# TODO_2: Print the user's list, one item per line
pass
elif choice == 'Q':
# TODO_1: Quit the program be exiting the loop
pass
else:
print('I don\'t understand. Please try again!')
print('Thanks for shopping!')
```
%% Cell type:code id: tags:
``` python
# TODO: Complete the profanity filter
def profanity_filter(sentence, bad_words):
''' replaces all instances of any word in bad_words with
a word with the first letter and then @s and the same length.
Inputs are sentence (a string) and bad_words (a list of strings)
Returns a string with bad_words replaced.
'''
pass
bad_word_list = ["darn", "heck", "crud", "exam"]
profanity_filter("I unplugged that darn Alexa", bad_word_list)
# print(profanity_filter("What the heck was my boss thinking?", bad_word_list))
# print(profanity_filter("He is full of crud?", bad_word_list))
```
This diff is collapsed.
This diff is collapsed.
__student__ = []
def __init__():
import csv
"""This function will read in the csv_file and store it in a list of dictionaries"""
__student__.clear()
with open('cs220_survey_data.csv', mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
__student__.append(row)
def count():
"""This function will return the number of records in the dataset"""
return len(__student__)
def get_lecture(idx):
"""get_lecture(idx) returns the lecture of the student in row idx"""
return __student__[int(idx)]['Lecture']
def get_section(idx):
"""get_lecture(idx) returns the section of the student in row idx"""
return __student__[int(idx)]['Section']
def get_age(idx):
"""get_age(idx) returns the age of the student in row idx"""
return __student__[int(idx)]['Age']
def get_primary_major(idx):
"""get_primary_major(idx) returns the primary major of the student in row idx"""
return __student__[int(idx)]['Primary Major']
def get_other_majors(idx):
"""get_other_majors(idx) returns the other major of the student in row idx"""
return __student__[int(idx)]['Other Majors']
def get_secondary_majors(idx):
"""get_other_majors(idx) returns the secondary majors of the student in row idx"""
return __student__[int(idx)]['Secondary Majors']
def get_zip_code(idx):
"""get_zip_code(idx) returns the residential zip code of the student in row idx"""
return __student__[int(idx)]['Zip Code']
def get_latitude(idx):
"""get_zip_code(idx) returns the favorite latitude of the student in row idx"""
return __student__[int(idx)]['Latitude']
def get_longitude(idx):
"""get_zip_code(idx) returns the favorite longitude of the student in row idx"""
return __student__[int(idx)]['Longitude']
def get_pizza_topping(idx):
"""get_pizza_topping(idx) returns the preferred pizza toppings of the student in row idx"""
return __student__[int(idx)]['Pizza Topping']
def get_cats_or_dogs(idx):
"""get_cats_or_dogs(idx) returns whether student in row idx likes cats or dogs"""
return __student__[int(idx)]['Cats or Dogs']
def get_runner(idx):
"""get_runner(idx) returns whether student in row idx is a runner"""
return __student__[int(idx)]['Runner']
def get_sleep_habit(idx):
"""get_sleep_habit(idx) returns the sleep habit of the student in row idx"""
return __student__[int(idx)]['Sleep Habit']
def get_procrastinator(idx):
"""get_procrastinator(idx) returns whether student in row idx is a procrastinator"""
return __student__[int(idx)]['Procrastinator']
def get_song(idx):
"""get_procrastinator(idx) returns the student in row idx favorite song"""
return __student__[int(idx)]['Song']
__init__()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment