|
| 1 | + |
| 2 | +List Lab |
| 3 | +############# |
| 4 | + |
| 5 | +Modeled after <http://www.upriss.org.uk/python/session5.html> |
| 6 | + |
| 7 | + |
| 8 | +Examples |
| 9 | +=================== |
| 10 | + zoo = ["giraffe", "crow"] # define a list |
| 11 | + zoo[0] # a single element |
| 12 | + zoo[0] = "zebra" # change an element |
| 13 | + zoo.append("marmot") # add element at end of list |
| 14 | + zoo = ["cat"] + zoo # add element at beginning |
| 15 | + type(raw_input("Type a string: ")) # returns str |
| 16 | + type( input("Type a number: ")) # returns int or float |
| 17 | + [x for x in zoo if len(x) > 4] # list comprehension |
| 18 | + zoo2 = zoo[:] # create a list copy |
| 19 | + zoo.pop() # delete last element |
| 20 | + del zoo[0] # delete element by index |
| 21 | + zoo.remove('crow') # delete element by value |
| 22 | + "abc"[::-1] # reverse a string: "cba" |
| 23 | + # Unspecified range takes all; step value of -1 reverses. |
| 24 | +Exercises |
| 25 | +=============== |
| 26 | + |
| 27 | +1. |
| 28 | + - Create a list that contains "Apples", "Pears", "Oranges" and "Peaches". |
| 29 | + - Display the list. |
| 30 | + - Ask the user for another fruit and add it to the end of the list. |
| 31 | + - Display the list. |
| 32 | + - Ask the user for a number and display the number back to the user and the fruit corresponding to that number (on a 1-is-first basis). |
| 33 | + - Add another fruit to the beginning of the list using "+" and display the list. |
| 34 | + - Add another fruit to the beginning of the list using insert() and display the list. |
| 35 | + |
| 36 | + - Display all the fruits that begin with "P", using a for loop and then using a list comprehension. |
| 37 | + |
| 38 | +2. Using the list above: |
| 39 | + - Display the list. |
| 40 | + - Remove the last fruit from the list. |
| 41 | + - Display the list. |
| 42 | + - Ask the user for a fruit to delete and find it and delete it. |
| 43 | + - (Bonus: Multiply the list times two. Keep asking until a match is found. Once found, delete all occurrences.) |
| 44 | + |
| 45 | +3. Using the list in item 1: |
| 46 | + - Ask the user for input displaying a line like "Do you like apples?" |
| 47 | + - for each fruit in the list (making the fruit all lowercase). |
| 48 | + - For each "no", delete that fruit from the list. |
| 49 | + - Display the list. |
| 50 | + |
| 51 | +4. Using the list in item 1: |
| 52 | + - Make a copy of the list and reverse the letters in each fruit in the copy. |
| 53 | + - Delete the last item of the original list. Display the original list and the copy. |
0 commit comments