COMP1701-004
fall 2023
lec-16
Is November Over Yet?




PREDICT what this displays
if the user enters bar at the prompt.
def is_vowel(s: str) -> bool:
return s in "aeiou"
def blorp_index(s: str) -> int:
i = len(s) - 1
blorp_idx = -1
while i >= 0 and blorp_idx == -1:
c = s[i]
if is_vowel(c):
blorp_idx = i
i -= 1
return blorp_idx
def fun(s: str) -> str:
i = blorp_index(s)
return s[i]
def main() -> None:
response = input("> ")
c = fun(response)
print("That", "was", c, sep="-")
main()

let's talk about these things today:
⦾ lists: the concept
⦾ lists: making them
⦾ lists: referring to items in them
⦾ lists: iterating through them
⦾ lists: lists of lists
lists : the concept
lists : the concept
| s | t | r | i | n | g |
|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
|---|
The string type can be viewed as a sequence of characters in consecutive indexed boxes.
lists : the concept
| 112 | -4 | 9 |
|---|
| 0 | 1 | 2 |
|---|
The list type can be viewed as a sequence of whatever-you-want in consecutive indexed boxes.
list of ints
| 0.2 | 1.0 | -100.03 | -4.81 |
|---|
| 0 | 1 | 2 | 3 |
|---|
list of floats
| True | True | False | True | False |
|---|
| 0 | 1 | 2 | 3 | 4 |
|---|
list of bools
| "foo" | "hi there" |
|---|
| 0 | 1 |
|---|
list of strings
lists : the concept
You might be wondering "can I put different types of things in a list?"
| True | "cheese" | 42 | 3.14 | "toast" |
|---|
| 0 | 1 | 2 | 3 | 4 |
|---|
list of whatever-the-heck-you-want
Yeah. But don't.
🙋🏻♂️❓🙋🏻♀️Why do you suppose this is a bad idea?
lists : making them
lists : making them
Let's talk about
2 ways
of creating a list
lists : making them
Let's talk about
2 ways
of creating a list
Way the first: use [ ] notation
Yup. Now your brain has to deal with 2 meanings of [ ].
completed_tasks = []
toggled_on = [True]
midday_temps_c = [-4, -14, 3, 2, 0]
weighted_marks = [2.4, 3.1, 4.0]
gamer_handles = ["skinny", "lady-bug", "rickNmorty", "D00MZDAY"]an empty list
a list of length 1
a list of length 5
🙋🏻♂️❓🙋🏻♀️How else have you used [ ]?
lists : making them
Let's talk about
2 ways
of creating a list
Way the second: use split()
a_string = "My dog has fleas."
split_s = a_string.split()
print(split_s) # ['My', 'dog', 'has', 'fleas.']split() is an example of a method - it's a function that is "understood" by an object
You'll deal a lot more with objects in your second semester. In the meantime, just know that strings and lists have many useful methods they can use.
🙋🏻♂️❓🙋🏻♀️BTW - what string methods have you used so far?
You can always tell you're looking at a method because there's always a dot (.) in front of it.
lists : making them
Let's talk about
2 ways
of creating a list
some split() nuances
sentence = " My dog has fleas. "
split_result = sentence.split()
print(split_result) # predict!lots of spaces - and even some tabs!
- By default, split() uses whitespace as a delimiter.
- Leading and trailing whitespace is ignored.
- Adjacent whitespace is considered a single delimiter.
lists : making them
Let's talk about
2 ways
of creating a list
some more split() nuances
some_numbers = "1,2,3,4"
split_result = some_numbers.split(",")
print(split_result) # predict!- split() can use any string as a delimiter, if you pass one in.
- Be careful - the items in the resulting list are always strings!
lists : making them
Let's talk about
2 ways
of creating a list
even MORE split() nuances
some_strings = "ready;willing;;able;"
split_result = some_strings.split(";")
print(split_result) # predict!
- Be careful - once you pass in an argument, split() does NOT ignore leading/trailing delimiters and does NOT clump adjacent delimiters!
adjacent delimiters
trailing delimiter
lists : making them
Let's talk about
2 ways
of creating a list
predict what happens in these two cases
sentence = "1,2,3,4"
split_result = sentence.split()
print(split_result) # predict!sentence = "1, 2, 3, 4"
split_result = sentence.split(",")
print(split_result) # predict!
lists : referring to items
lists : referring to items
Good news, everyone!
We can refer to items in a list just like we can with letters in a string - with [ ]
"RHINO"[0] # "R"
response = "yes"
response[2] # What's this?["Aliens", "Jaws", "Hereditary"][1] # "Jaws"
temps = [-2, 0, 5, -13]
temps[2] # What's this?
"I am a wild party".split()[3] # What's this?The index operator with strings.
The index operator with lists.
🙋🏻♂️❓🙋🏻♀️What was the [ ] operator called?


lists : iterating through 'em
lists : iterating through
Good news, everyone!
We can iterate through items in a list just like we can with strings.
lists : iterating through
buncha_things = ["knock", "it", "off"]
number_of_things = len(buncha_things)
i = 0
while i < number_of_things:
curr_thing = buncha_things[i]
# do something with curr_thing
i += 1
get upper bound
initialize index counter LCV
grab next thing in list
bump up LCV
while style
counted loop
🙋🏻♂️❓🙋🏻♀️Why not just call len(buncha_things) in the while?
Does this seem pretty "busy", or is it just me?
lists : iterating through
buncha_things = ["knock", "it", "off"]
for curr_thing in buncha_things:
# do something with curr_thing
for style
so nice and quiet!
TASK
Make an app that takes in a sequence of integers separated by commas from a user and tells the user whether there are more odd numbers, or more even numbers, or the same number of both.
You should try NOT put everything in a main() - make 2 functions:
- a function that prompts the user and returns a list (of what)?
- a function that take in a list (of what?) and returns the number of even (or odd - your choice) numbers in that list
Numbers? 1,2,3,4,5
There are more odd numbers than even numbers in 1,2,3,4,5.Numbers? 11,14
There are the same number of even and odd numbers in 11,14.Numbers? 240
There are more even numbers than odd numbers in 240.
lists : lists of lists
Remember this?
| 112 | -4 | 9 |
|---|
| 0 | 1 | 2 |
|---|
list of ints
| 0.2 | 1.0 | -100.03 | -4.81 |
|---|
| 0 | 1 | 2 | 3 |
|---|
list of floats
| True | True | False | True | False |
|---|
| 0 | 1 | 2 | 3 | 4 |
|---|
list of bools
| "foo" | "hi there" |
|---|
| 0 | 1 |
|---|
list of strings
(ominous music plays)
| ["chicken", "beef"] | ["mashed potato", "baked potato"] | ["corn", "peas", "carrots"] |
|---|
| 0 | 1 | 2 |
|---|
list of lists
If a list can hold anything...
...then couldn't it hold another list?!?
lists : lists of lists

Here we go again!
lists : lists of lists
print(f"this is {cruel(and_unusual(punishment))}")This can hurt a bit - because any kind of nesting is challenging to the brain
if distance < 0:
if distance < 10 and limit >= DA_LIMIT:
if limit - fudge(factor) < 0:
print("please stop")
else:
print("no, really")
elif distance < 10 and limit < OTHER_LIMIT:
print("I'm begging you")
else:
print("my brain feels funny")
else:
print("<...passes out...>")def display_number_triangle(
lower_bound,
upper_bound,
step_size):
line_starting_num = lower_bound
while line_starting_num < upper_bound:
curr_num = line_starting_num
while curr_num < upper_bound:
print(curr_num, end="")
curr_num += step_size
print()
line_starting_num += step_sizechoices = [["beef", "pork"], ["pasta", "potatoes"],["peas", "carrots"]]lists : lists of lists
Good news, everyone!
We can still refer to items in a list of lists just like we can with a simple list - with [ ]
Bad news, everyone!
This can be confusing and frustrating.
lists : lists of lists
movies = [
["Aliens", ""], # action genre
[], # horror
[], # comedy
]Let's do some live practice!
Help me make a nested list of movies, then we'll practice our index skillz.
lec-16
By Jordan Pratt
lec-16
list creation ([ ], split) | list iteration | list item reference | list of lists
- 200