CS170: Programming for the World Around Us - Lists with Python
Activity Goals
The goals of this activity are:- To design and implement algorithms using lists
- To be able to explain that a list is an ordered collection of data
- To be able to create a list and assign its elements
- To be able to access an element from a list by its index
- To explain that strings are lists of characters, and to manipulate them accordingly
- To be able to iterate over a list
- To create an manipulate multidimensional lists
Supplemental Reading
Feel free to visit these resources for supplemental background reading material.The Activity
Directions
Consider the activity models and answer the questions provided. First reflect on these questions on your own briefly, before discussing and comparing your thoughts with your group. Appoint one member of your group to discuss your findings with the class, and the rest of the group should help that member prepare their response. Answer each question individually from the activity, and compare with your group to prepare for our whole-class discussion. After class, think about the questions in the reflective prompt and respond to those individually in your notebook. Report out on areas of disagreement or items for which you and your group identified alternative approaches. Write down and report out questions you encountered along the way for group discussion.Model 1: Lists in Python
1 2 3 4 5 6 7 | grades = [] for i in range ( 10 ): grades.append( 90 + i) for i in range ( len (grades)): print (grades[i]) |
Questions
- Comment each line of this program. What do you think it does? Try running it.
- What is the size of the
grades
list? - What are the indices of the
grades
list? - How would you modify the program above to play a game of "Duck-Duck-Goose" -- that is, iterating through the array until a certain value is reached (say,
92
), and printing that index where it is found?
Model 2: Comparing Lists in Python
1 2 | list1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] list2 = [ 1 , 2 , 3 , 4 , 5 ] |
Questions
- Write a loop to check if these two lists are the same (that is, have the same size and contain the same values).
- What do you think
del list1[5]
does? Try it and then see if your lists are the same! - Comment out the
del
line, and trylist2.insert(4, 6)
instead. - What does
list1.extend(list2)
do? Print it out and see.
Model 3: 2D Lists in Python
1 2 3 4 | schedule = [ [ "9 AM" , "ECON101" ], [ "10 AM" , "CS173" ] ] |
Questions
- Write a program to print your daily schedule.
- Modify this program to add a third dimension to the list representing each day of the week.
Model 4: Strings in Python
1 2 3 4 | str = "The quick brown fox jumped over the lazy dog." words = str .split( " " ) for word in words: print ( "{} has length {}" . format (word, len (word)) |
Questions
- What does this program do when you run it?
- What are strings in Python?