Python Lists

Ace your homework & exams now with Quizwiz!

prices= { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }

Investing in Stock Good work! As a store manager, you're also in charge of keeping track of your stock/inventory. Instructions 1. Create a stock dictionary with the values below. "banana": 6, "apple": 0, "orange": 32, "pear": 15

start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for number in start_list: square_list.append(number ** 2) square_list.sort() print square_list ... [1, 4, 9, 16, 25]

More with 'for' If your list is a jumbled mess, you may need to sort() it. animals = ["cat", "ant", "bat"] animals.sort() for animal in animals: print animal First, we create a list called animals with three strings. The strings are not in alphabetical order. Then, we sort animals into alphabetical order. Note that .sort() modifies the list rather than returning a new list. Then, for each item in animals, we print that item out as "ant", "bat", "cat" on their own line each. Instructions 1. Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. Then sort square_list!

my_list = [1,9,3,8,5,7] for number in my_list: print 2 * number # Your code here ... 2 18 6 16 10 14

For One and All If you want to do something with every item in the list, you can use a for loop. If you've learned about for loops in JavaScript, pay close attention! They're different in Python. for variable in list_name: # Do stuff! A variable name follows the for keyword; it will be assigned the value of each list item in turn. Then in list_name designates list_name as the list the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list. Instructions 1. Write a statement in the indented part of the for-loop that prints a number equal to 2 * number for every list item.

numbers = [5, 6, 7, 8] print "Adding the numbers at indices 0 and 2..." print numbers[0] + numbers[2] print "Adding the numbers at indices 1 and 3..." print numbers[1] + numbers[3] ... Adding the numbers at indices 0 and 2... 12 Adding the numbers at indices 1 and 3... 14

Access by Index You can access an individual item on the list by its index. An index is like an address that identifies the item's place in the list. The index appears directly after the list name, in between brackets, like this: list_name[index]. List indices begin with 0, not 1! You access the first item in a list like this: list_name[0]. The second item in a list is at index 1: list_name[1]. Computer scientists love to start counting from zero. Instructions 1. Write a statement that prints the result of adding the second and fourth items of the list. Make sure to access the list by index!

names = ["Adam","Alex","Mariah","Martine","Columbus"] for x in names: print x ... Adam Alex Mariah Martine Columbus

BeFOR We Begin Before we begin our exercise, we should go over the Python for loop one more time. For now, we are only going to go over the for loop in terms of how it relates to lists and dictionaries. We'll explain more cool for loop uses in later courses. for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as follows: a = ["List", "of", "some", "sort"] for x in a: # Do something for every x This loop will run all of the code in the indented block under the for x in a: statement. The item in the list that is currently being evaluated will be x. So running the following: for item in [1, 3, 21]: print item would print 1, then 3, and then 21. The variable between for and in can be set to any variable name (currently item), but you should be careful to avoid using the word list as a variable, since that's a reserved word (that is, it means something special) in the Python language. Instructions 1. Use a for loop to print out all of the elements in the list names.

# key - animal_name : value - location zoo_animals = { 'Unicorn' : 'Cotton Candy House', 'Sloth' : 'Rainforest Exhibit', 'Bengal Tiger' : 'Jungle House', 'Atlantic Puffin' : 'Arctic Exhibit', 'Rockhopper Penguin' : 'Arctic Exhibit' } # A dictionary (or list) declaration may break across multiple lines # Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.) del zoo_animals['Unicorn'] # Your code here! del zoo_animals['Sloth'] del zoo_animals['Bengal Tiger'] zoo_animals['Rockhopper Penguin'] = 'Jungle House' print zoo_animals ... {'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Jungle House'}

Changing Your Mind Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with the del command: del dict_name[key_name] will remove the key key_name and its associated value from the dictionary. A new value can be associated with a key by assigning a value to the key, like so: dict_name[key] = new_value Instructions 1. Delete the 'Sloth' and 'Bengal Tiger' items from zoo_animals using del. Set the value associated with 'Rockhopper Penguin' to anything other than 'Arctic Exhibit'.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for number in a: if number % 2 == 0: print number ... 0 2 4 6 8 10 12

Control Flow and Looping The blocks of code in a for loop can be as big or as small as they need to be. While looping, you may want to perform different actions depending on the particular item in the list. numbers = [1, 3, 4, 7] for number in numbers: if number > 6: print number print "We printed 7." In the above example, we create a list with 4 numbers in it. Then we loop through the numbers list and store each item in the list in the variable number. On each loop, if number is greater than 6, we print it out. So, we print 7. Finally, we print out a sentence. Make sure to keep track of your indentation or you may get confused! Instructions 1. Like step 2 above, loop through each item in the list called a. Like step 3 above, if the number is even, print it out. You can test if the item % 2 == 0 to help you out.

zoo_animals = ["pangolin", "cassowary", "sloth", "dog"]; # One animal is missing! if len(zoo_animals) > 3: print "The first animal at the zoo is the " + zoo_animals[0] print "The second animal at the zoo is the " + zoo_animals[1] print "The third animal at the zoo is the " + zoo_animals[2] print "The fourth animal at the zoo is the " + zoo_animals[3] ... The first animal at the zoo is the pangolin The second animal at the zoo is the cassowary The third animal at the zoo is the sloth The fourth animal at the zoo is the dog

Introduction to Lists Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name. (Datatypes you've already learned about include strings, numbers, and booleans.) You can assign items to a list with an expression of the form list_name = [item_1, item_2] with the items in between brackets. A list can also be empty: empty_list = []. Lists are very similar to strings, but there are a few key differences. Instructions 1. The list zoo_animals has three items (check them out on line 1). Go ahead and add a fourth! Just enter the name of your favorite animal (as a "string") on line 1, after the final comma but before the closing ].

inventory = { 'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } # Adding a key 'burlap bag' and assigning a list to it inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth'] # Sorting the list found under the key 'pouch' inventory['pouch'].sort() # Your code here inventory['pocket'] = ['seashell', 'strange berry', 'lint'] inventory['backpack'].sort() inventory['backpack'].remove('dagger') inventory['gold'] = inventory['gold'] + 50

It's Dangerous to Go Alone! Take This Let's go over a few last notes about dictionaries my_dict = { "fish": ["c", "a", "r", "p"], "cash": -4483, "luck": "good" } print my_dict["fish"][0] In the example above, we created a dictionary that holds many types of values. The key "fish" has a list, the key "cash" has an int, and the key "luck" has a string. Finally, we print the letter "c". When we access a value in the dictionary like my_dict["fish"], we have direct access to that value (which happens to be a list). We can access the item at index 0 in the list stored by the key "fish". 1. Add a key to inventory called 'pocket' Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint' .sort() the items in the list stored under the 'backpack' key Then .remove('dagger') from the list of items stored under the 'backpack' key Add 50 to the number stored under the 'gold' key Hint You can use methods with a list stored in a dictionary as follows: dict_name['list_key'].method() For example, since 'backpack' is a key in our dictionary inventory you can delete 'dagger' from the corresponding list like this: inventory['backpack'].remove('dagger')

suitcase = [] suitcase.append("sunglasses") # Your code here! suitcase.append("hat") suitcase.append("coat") suitcase.append("shoes") list_length = len(suitcase) # Set this to the length of suitcase print "There are %d items in the suitcase." % (list_length) print suitcase ... There are 4 items in the suitcase. ['sunglasses', 'hat', 'coat', 'shoes']

Late Arrivals & List Length A list doesn't have to have a fixed length. You can add items to the end of a list any time you like! letters = ['a', 'b', 'c'] letters.append('d') print len(letters) print letters In the above example, we first create a list called letters. Then, we add the string 'd' to the end of the letters list. Next, we print out 4, the length of the letters list. Finally, we print out ['a', 'b', 'c', 'd']. Instructions 1. On lines 5, 6, and 7, append three more items to the suitcase list, just like the second line of the example above. (Maybe bring a bathing suit?) Then, set list_length equal to the length of the suitcase list.

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"] # The first and second items (index zero and one) first = suitcase[0:2] # Third and fourth items (index two and three) middle = suitcase[2:4] # The last two items (index four and five) last = suitcase[4:6]

List Slicing Sometimes, you only want to access a portion of a list. letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3] print slice print letters In the above example, we first create a list called letters. Then, we take a subsection and store it in the slice list. We start at the index before the colon and continue up to but not including the index after the colon. Next, we print out ['b', 'c']. Remember that we start counting indices from 0 and that we stopped before index 3. Finally, we print out ['a', 'b', 'c', 'd', 'e'], just to show that we did not modify the original letters list. Instructions 1. On line 7, create a list called middle containing only the two middle items from suitcase. On line 10, create a list called last made up only of the last two items from suitcase.

# Write your function below! def fizz_count(x): count = 0 for n in x: if n == 'fizz': count = count + 1 return count strings = ["fizz","cat","fizz"] fizz = fizz_count(strings) print fizz

Lists + Functions Functions can also take lists as inputs and perform various operations on those lists. def count_small(numbers): total = 0 for n in numbers: if n < 10: total = total + 1 return total lotto = [4, 8, 15, 16, 23, 42] small = count_small(lotto) print small In the above example, we define a function count_small that has one parameter, numbers. We initialize a variable total that we can use in the for loop. For each item n in numbers, if n is less than 10, we increment total. After the for loop, we return total. After the function definition, we create an array of numbers called lotto. We call the count_small function, pass in lotto, and store the returned result in small. Finally, we print out the returned result, which is 2 since only 4 and 8 are less than 10. 1. Write a function that counts how many times the string "fizz" appears in a list. Write a function called fizz_count that takes a list x as input. Create a variable count to hold the ongoing count. Initialize it to zero. for each item in x:, if that item is equal to the string "fizz" then increment the count variable. After the loop, please return the count variable. For example, fizz_count(["fizz","cat","fizz"]) should return 2.

prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, } for key in prices: print key print "price: %s" % prices[key] print "stock: %s" % stock[key] ... orange price: 1.5 stock: 32 pear price: 3 stock: 15 banana price: 4 stock: 6 apple price: 2 stock: 0

Loop through each key in prices. Like the example above, for each key, print out the key along with its price and stock information. Print the answer in the following format: apple price: 2 stock: 0 Like the example above, because you know that the prices and stock dictionary have the same keys, you can access the stock dictionary while you are looping through prices. When you're printing, you can use the syntax from the example above.

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # Use index() to find "duck" # Your code here! animals.insert(duck_index, "cobra") print animals # Observe what prints after the insert operation ... ['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']

Maintaining Order Sometimes you need to search for an item in a list. animals = ["ant", "bat", "cat"] print animals.index("bat") First, we create a list called animals with three strings. Then, we print the first index that contains the string "bat", which will print 1. We can also insert items into a list. animals.insert(1, "dog") print animals We insert "dog" at index 1, which moves everything down by 1. We print out ["ant", "dog", "bat", "cat"] Instructions 1. Use the .index(item) function to find the index of "duck". Assign that result to a variable called duck_index. Then .insert(index, item) the string "cobra" at that index.

menu = {} # Empty dictionary menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair print menu['Chicken Alfredo'] # Your code here: Add some dish-price pairs to menu! menu['Spam'] = 2.50 menu['Eggs'] = 4.50 menu['Cheese'] = 6.00 print "There are " + str(len(menu)) + " items on the menu." print menu ... 14.5 There are 4 items on the menu. {'Cheese': 6.0, 'Chicken Alfredo': 14.5, 'Eggs': 4.5, 'Spam': 2.5}

New Entries Like Lists, Dictionaries are mutable. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created like so: dict_name[new_key] = new_value An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list. The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That's right: you can put lists inside dictionaries!) Instructions 1. Add at least three more key-value pairs to the menu variable, with the dish name (as a "string") for the key and the price (a float or integer) as the value. Here's an example: menu['Spam'] = 2.50

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] # Last night our zoo's sloth brutally attacked # the poor tiger and ate it whole. # The ferocious sloth has been replaced by a friendly hyena. zoo_animals[2] = "hyena" # What shall fill the void left by our dear departed tiger? # Your code here! zoo_animals[3] = "dog"

New Neighbors A list index behaves like any other variable name! It can be used to access as well as assign values. You saw how to access a list index like this: zoo_animals[0] # Gets the value "pangolin" You can see how assignment works on line 5: zoo_animals[2] = "hyena" # Changes "sloth" to "hyena" Instructions 1. Write an assignment statement that will replace the item that currently holds the value "tiger" with another animal (as a string). It can be any animal you like.

backpack = ['xylophone', 'dagger', 'tent', 'bread loaf'] backpack.remove('dagger')

Remove a Few Things Sometimes you need to remove something from a list. beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatles This code will print: ["john","paul","george","ringo"] We create a list called beatles with 5 strings. Then, we remove the first item from beatles that matches the string "stuart". Note that .remove(item) does not return anything. Finally, we print out that list just to see that "stuart" was actually removed. Instructions 1. Remove 'dagger' from the list of items stored in the backpack variable.

animals = "catdogfrog" # The first three characters of animals cat = animals[:3] # The fourth through sixth characters dog = animals[3:6] # From the seventh character to the end frog = animals[6:]

Slicing Lists and Strings You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each character is a sequential item in the list, starting from index 0. my_list[:2] # Grabs the first two items my_list[3:] # Grabs the fourth through last items If your list slice includes the very first or last item in a list (or a string), the index for that item doesn't have to be included. Instructions 1. Assign to dog a slice of animals from index 3 up until but not including index 6. Assign to frog a slice of animals from index 6 until the end of the string.

for letter in "Codecademy": print letter # Empty lines to make the output pretty print print word = "Programming is fun!" for letter in word: # Only print out the letter i if letter == "i": print letter ... C o d e c a d e m y i i

String Looping As we've mentioned, strings are like lists with characters as elements. You can loop through strings the same way you loop through lists! While we won't ask you to do that in this section, we've put an example in the editor of how looping through a string might work. Instructions 1. Run the code to see string iteration in action!

# Assigning a dictionary with three key-value pairs to residents: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['Puffin'] print residents['Sloth'] print residents['Burmese Python'] # Prints Puffin's room number # Your code here! ... 104 105 106

This Next Part is Key A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so: d = {'key1' : 1, 'key2' : 2, 'key3' : 3} This is a dictionary called d with three key-value pairs. The key 'key1' points to the value 1, 'key2' to 2, and so on. Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username), and more! Instructions 1. Print the values stored under the 'Sloth' and 'Burmese Python' keys. Accessing dictionary values by key is just like accessing list values by index: residents['Puffin']# Gets the value 104 Check the Hint if you need help!

webster = { "Aardvark" : "A star of a popular children's cartoon show.", "Baa" : "The sound a goat makes.", "Carpet": "Goes on the floor.", "Dab": "A small amount." } # Add your code below! for x in webster: print webster[x] ... A star of a popular children's cartoon show. Goes on the floor. A small amount. The sound a goat makes.

This is KEY! You can also use a for loop on a dictionary to loop through its keys with the following: # A simple dictionary d = {"foo" : "bar"} for key in d: print d[key] # prints "bar" Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order. Instructions 1. Use a for loop to go through the webster dictionary and print out all of the definitions. Hint The definitions are the values associated with each key. print webster["Aardvark"] will give you an output of "A star of a popular children's cartoon show." Since you can loop through every key, you should be able to get every value

prices= { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }

Your Own Store! Okay—on to the core of our project. Congratulations! You are now the proud owner of your very own Codecademy brand supermarket. animal_counts = { "ant": 3, "bear": 6, "crow": 2 } In the example above, we create a new dictionary called animal_counts with three entries. One of the entries has the key "ant" and the value 3. Instructions 1. Create a new dictionary called prices using {} format like the example above. Put these values in your prices dictionary, in between the {}: "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 Yeah, this place is really expensive. (Your supermarket subsidizes the zoo from the last course.)


Related study sets

Unit #1 Practice Questions (60 questions)

View Set

Bio 122 Study Guide Chapter 16: The Molecular Basis of Inheritance

View Set

Macroeconomics chapters 1, 2, 23, 24, 25, 26, Chapter 35, Chapter 33, Macroeconomics chapt 28, Chapt 27 Macroeconomics

View Set