In-Class Coding Lab: Lists

The goals of this lab are to help you understand:

  • List indexing and slicing
  • List methods such as insert, append, find, delete
  • How to iterate over lists with loops

Python Lists work like Real-Life Lists

In real life, we make lists all the time. To-Do lists. Shopping lists. Reading lists. These lists are collections of items, for example here's my shopping list:

 Milk, Eggs, Bread, Beer

There are 4 items in this list.

Likewise, we can make a similar list in Python, and count the number of items in the list using the len() function:


In [ ]:
shopping_list = [ 'Milk', 'Eggs', 'Bread', 'Beer']
item_count = len(shopping_list)
print("List: %s has %d items" % (shopping_list, item_count))

Enumerating Your List Items

In real-life, we enumerate lists all the time. We go through the items on our list one at a time and make a decision, for example: "Did I add that to my shopping cart yet?"

In Python we go through items in our lists with the for loop. We use for because the number of items is pre-determined and thus a definite loop is the appropriate choice.

Here's an example:


In [ ]:
for item in shopping_list:
    print("I need to buy some %s " % (item))

In [ ]:
# or with f-strings
for item in shopping_list:
    print(f"I need to buy some {item}")

Now You Try It!

Write code in the space below to print each stock on its own line.


In [ ]:
stocks = [ 'IBM', 'AAPL', 'GOOG', 'MSFT', 'TWTR', 'FB']
#TODO: Write code here

Indexing Lists

Sometimes we refer to our items by their place in the list. For example "Milk is the first item on the list" or "Beer is the last item on the list."

We can also do this in Python, and it is called indexing the list.

IMPORTANT The first item in a Python lists starts at index 0.


In [ ]:
print("The first item in the list is:", shopping_list[0]) 
print("The last item in the list is:", shopping_list[3])   
print("This is also the last item in the list:", shopping_list[-1])  
print("This is the second to last item in the list:", shopping_list[-2])

For Loop with Index

You can also loop through your Python list using an index. In this case we use the range() function to determine how many times we should loop:


In [ ]:
for i in range(len(shopping_list)):
    print("I need to buy some %s " % (shopping_list[i]))

Now You Try It!

Write code to print the 2nd and 4th stocks in the list variable stocks. For example:

AAPL MSFT


In [ ]:
#TODO: Write code here

Lists are Mutable

Unlike strings, lists are mutable. This means we can change a value in the list.

For example, I want 'Craft Beer' not just 'Beer':


In [ ]:
print(shopping_list)
shopping_list[-1] = 'Craft Beer'
print(shopping_list)

List Methods

In your readings and class lecture, you encountered some list methods. These allow us to maniupulate the list by adding or removing items.


In [ ]:
print("Shopping List: %s" %(shopping_list))

print("Adding 'Cheese' to the end of the list...")
shopping_list.append('Cheese')  #add to end of list
print("Shopping List: %s" %(shopping_list))

print("Adding 'Cereal' to position 0  in the list...")
shopping_list.insert(0,'Cereal') # add to the beginning of the list (position 0)
print("Shopping List: %s" %(shopping_list))

print("Removing 'Cheese' from the list...")
shopping_list.remove('Cheese')  # remove 'Cheese' from the list
print("Shopping List: %s" %(shopping_list))

print("Removing item from position 0 in the list...")
del shopping_list[0]   # remove item at position 0
print("Shopping List: %s" %(shopping_list))

Now You Try It!

Write a program to remove the following stocks: IBM and TWTR

Then add this stock to the end NFLX and this stock to the beginning TSLA

Print your list when you are done. It should look like this:

['TSLA', 'AAPL', 'GOOG', 'MSFT', 'FB', 'NFLX']


In [ ]:
# TODO: Write Code here

Sorting

Since Lists are mutable. You can use the sort() method to re-arrange the items in the list alphabetically (or numerically if it's a list of numbers)


In [ ]:
print("Before Sort:", shopping_list)
shopping_list.sort() 
print("After Sort:", shopping_list)

Putting it all together

Winning Lotto numbers. When the lotto numbers are drawn, they are in any order, when they are presented they're allways sorted. Let's write a program to input 5 numbers then output them sorted

1. for i in range(5)
2.    input a number
3.    append the number you input to the lotto_numbers list
4. sort the lotto_numbers list
5. print the lotto_numbers list like this: 
   'today's winning numbers are [1, 5, 17, 34, 56]'

In [ ]:
## TODO: Write program here:

lotto_numbers = []  # start with an empty list

Metacognition

Please answer the following questions. This should be a personal narrative, in your own voice. Answer the questions by double clicking on the question and placing your answer next to the Answer: prompt.

Questions

  1. Record any questions you have about this lab that you would like to ask in recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking.

Answer:

  1. What was the most difficult aspect of completing this lab? Least difficult?

Answer:

  1. What aspects of this lab do you find most valuable? Least valuable?

Answer:

  1. Rate your comfort level with this week's material so far.

1 ==> I can do this on my own and explain how to do it.
2 ==> I can do this on my own without any help.
3 ==> I can do this with help or guidance from others. If you choose this level please list those who helped you.
4 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand.

Answer:


In [ ]:
# SAVE YOUR WORK FIRST! CTRL+S
# RUN THIS CODE CELL TO TURN IN YOUR WORK!
from ist256.submission import Submission
Submission().submit()