Skip to content
Snippets Groups Projects
Commit 38182c44 authored by Anna Meyer's avatar Anna Meyer
Browse files

list code template change

parent 3559f1e3
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Lists
%% Cell type:code id: tags:
``` python
import project
```
%% Cell type:code id: tags:
``` python
# Warmup: string review
# Predict the output of the following statments
name = "Andrew"
print(name[3])
print(name[-1])
print(name[:2])
print(name[:-1])
# Try this: change only the last letter of the name to "a" so that name = "Andrea"
# Takeaway:
# you cannot _______________
# because strings are ___________-
# But what about....
name = "Fred" # this is called reassignment and is allowed
print(name)
```
%% Cell type:markdown id: tags:
## Learning Objectives
%% Cell type:markdown id: tags:
- 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
- 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:
### Motivation for lists:
- what if we want to store a sequence of numbers or a sequence of numbers and strings?
- lists enable us to create flexible sequences: we can store anything inside a list as item, including:
- int
- float
- str
- bool
- other lists, etc.,
%% Cell type:code id: tags:
``` python
day = "Monday"
# first quotation indicates beginning of string sequence
# second quotation indicates end of string sequence
```
%% Cell type:code id: tags:
``` python
empty_list = None
some_nums = None
# [ indicates beginning of sequence
# ] indicates end of sequence
```
%% Cell type:code id: tags:
``` python
grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"]
# TODO: compute length of grocery_list
print()
# TODO: use indexing to display broccoli
print()
# TODO: use indexing to display last item
print()
# TODO: use slicing to extract only the vegetables
print()
```
%% Cell type:code id: tags:
``` python
# TODO: discuss why the following gives IndexError
print(grocery_list[len(grocery_list)])
```
%% Cell type:markdown id: tags:
#### Write loops that process lists
%% Cell type:code id: tags:
``` python
# Iterate over every item in grocery_list to display:
# <Item> purchased!
for item in ???:
print()
```
%% Cell type:code id: tags:
``` python
# Compute sum of numbers in some_nums
# Let's do this example using PythonTutor
total = 0
# TODO: for loop to iterate over each number in some_nums
print(total)
```
%% Cell type:code id: tags:
``` python
# We can use a list instead of a variable for each operation
[10, 20, 30][1]
```
%% Cell type:code id: tags:
``` python
# We can use a list instead of a variable for each operation
[10, 20, 30][1:]
```
%% Cell type:markdown id: tags:
How does Python differentiate between two different usages of `[]`?
%% 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 one.'''
max_length = 0
longest_word = None
return longest_word
print(grocery_list)
print(longest_word(grocery_list))
print(longest_word(["aaaa", "xyz", "hello"]))
print(longest_word([]))
```
%% Cell type:markdown id: tags:
### Other sequence operations
- concatentation using `+`
- `in`
- multiply by an `int`
%% Cell type:code id: tags:
``` python
msg = "Happy "
print(msg + "Monday :)")
some_nums = [11, 22, 33, 44]
print(some_nums + [1, 2, 3]) # `+` concatenates two lists
```
%% Cell type:code id: tags:
``` python
msg = "Happy"
print("H" in msg)
print("h" in msg)
some_nums = [11, 22, 33, 44]
print(33 in some_nums)
print(55 in some_nums)
```
%% Cell type:code id: tags:
``` python
msg = "Happy :)"
print(msg * 3)
print(["Go", "Badgers!"] * 3)
```
%% Cell type:markdown id: tags:
## Strings versus lists
<div>
<img src="attachment:Mutation.png" width="600"/>
</div>
%% Cell type:markdown id: tags:
### Difference 1: lists are flexible
%% Cell type:code id: tags:
``` python
# String sequence can only contain characters as items
# List sequence can contain anything as an item
l = ["hello", 14, True, 5.678, None, ["list", "inside", "a", "list"]]
# TODO: fix the bug in this loop
for i in l:
print(l[i])
# TODO: use indexing to extract and print the inner list
print()
# TODO: print type of last item in l
print()
# TODO: use double indexing to extract "inside"
print()
```
%% Cell type:code id: tags:
``` python
# List of lists usecase example
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:markdown id: tags:
### Difference 2: lists are mutable
<div>
<img src="attachment:Mutability.png" width="600"/>
</div>
- Mutability has nothing to do with variable assignments / re-assignments
- Mutability has to do with changing values inside a sequence
%% Cell type:code id: tags:
``` python
# Variables can always be re-assigned
s = "AB"
s = "CD"
s += "E"
print(s)
nums = [1, 2]
nums = [3, 4]
print(nums)
```
%% Cell type:code id: tags:
``` python
name = "Andrew"
# TODO: let's try to change "Andrew" to "Andrea"
# doesn't work because strings are immutable, that is you cannot change the value inside an existing string
```
%% Cell type:code id: tags:
``` python
nums = [2, 2, 9]
# TODO: change 9 to 0
print(nums)
# works because lists are mutable, that is you can change the value inside an existing list
```
%% Cell type:markdown id: tags:
### Mutating a list
- update using index (works only for existing index)
- `append` method
- `extend` method
- `pop` method
- `sort` method
Unlike string methods, list methods mutate the original list. String methods produce a new string because strings are immutable.
%% Cell type:code id: tags:
``` python
grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"]
# TODO: try to add "blueberries" at index 5
grocery_list[???] = "blueberries"
# doesn't work because grocery_list does not contain a previous item at index 5
```
%% Cell type:markdown id: tags:
So, how do we add a new item to a list?
%% Cell type:code id: tags:
``` python
grocery_list.append("blueberries")
print(grocery_list)
```
%% Cell type:markdown id: tags:
Can we add multiple items using `append`?
%% Cell type:code id: tags:
``` python
# Let's try to add "peanut butter", "jelly", "bread"
grocery_list.append()# doesn't work because append only accepts a single argument
```
%% Cell type:code id: tags:
``` python
grocery_list.append()# adds the list argument as such
print(grocery_list)
```
%% Cell type:markdown id: tags:
`extend` method will enable us to add every item in argument list to the original list as individual item.
%% Cell type:code id: tags:
``` python
grocery_list.extend(["falafel", "pita bread", "hummus"])
print(grocery_list)
```
%% Cell type:markdown id: tags:
`pop` enables us to remove item from the list:
- by default pop() removes the last item from the list
- you can override that by passing an index as argument
- pop remove the item from the original list and also returns it
%% Cell type:code id: tags:
``` python
grocery_list.pop()
```
%% Cell type:code id: tags:
``` python
grocery_list
```
%% Cell type:code id: tags:
``` python
# TODO: remove "oranges" from grocery_list and store it into a variable
some_fruit = grocery_list.pop(???)
print(some_fruit)
print(grocery_list)
```
%% Cell type:markdown id: tags:
`sort` method enables us to sort the list using alphanumeric ordering.
TODO: Try sorting each of the following lists.
%% Cell type:code id: tags:
``` python
L = None # TODO: initialize list with some unordered numbers
L
```
%% Cell type:code id: tags:
``` python
L = None # TODO: initialize list with some unordered strings
L
```
%% Cell type:code id: tags:
``` python
L = [False, True, False, True, True]
L
```
%% Cell type:code id: tags:
``` python
L = ["str", 1, 2.0, False]
L.sort() # Doesn't work as you cannot compare different types!
```
%% Cell type:markdown id: tags:
`split` method splits a string into a list of strings, using a separator (argument)
- Syntax: some_string.split(separator_string)
%% Cell type:code id: tags:
``` python
sentence = "a,quick,brown,fox"
words = sentence.split(",")
words
```
%% Cell type:markdown id: tags:
`join` method joins a list of strings into a single string using a separator (argument)
- Syntax: separator_string.join(some_list)
%% Cell type:code id: tags:
``` python
characters = ["M", "SS", "SS", "PP", ""]
place = "I".join(characters)
place
# TODO: remove the last item in characters list and see what place you get (re-run cell)
```
%% Cell type:markdown id: tags:
### List all Engineering majors (primary major) among current lecture (example: LEC001) students
%% Cell type:code id: tags:
``` python
for idx in range(project.count()):
lecture = project.get_lecture(idx)
major = project.get_primary_major(idx)
if lecture == "LEC001":
print(lecture, major)
```
%% Cell type:markdown id: tags:
### Profanity filtering
%% Cell type:code id: tags:
``` python
bad_words = ["omg", "midterm", "exam"]
def censor(input_string):
"""
replaces every bad word in input string with that word's first
letter and then * for the remaining characters
"""
# TODO: use split to extract every word
# TODO: Iterate over every word: 1. check if word is in bad_words 2. compute replacement 3. replace word
# TODO: join the words back using the correct separator and return the joined string
censor("omg the midterm was so awesome!")
```
%% Cell type:markdown id: tags:
### Wordle (self-study example)
%% Cell type:code id: tags:
``` python
def get_wordle_results(guess):
wordle_result = ""
for i in range(len(guess)):
if guess[i] == word_of_the_day[i]:
wordle_result += "O"
elif word_of_the_day.find(guess[i]) != -1:
wordle_result += "_"
else:
wordle_result += "X"
return wordle_result
max_num_guesses = 6
current_num_guesses = 1
word_of_the_day = "CRANE"
print("Welcome to PyWordle!")
print("You have 6 guesses to guess a 5 character word.")
print("X\tThe letter is not in the word.")
print("_\tThe letter is in the word, but in the wrong place.")
print("O\tThe letter is in the correct place!")
while current_num_guesses <= max_num_guesses:
guess = input("Guess the word: ")
guess = guess.upper()
wordle_results = get_wordle_results(guess)
print("{}\t{}".format(guess, wordle_results))
if guess == word_of_the_day:
break
current_num_guesses += 1
if current_num_guesses > max_num_guesses:
print("Better luck next time!")
print("The word was: {}".format(word_of_the_day))
else:
print("You won in {} guesses!".format(current_num_guesses))
```
%% Cell type:code id: tags:
``` python
```
......
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