Text Size
Text Size
Exit Full Screen
Python3 Editor
Show
Source Code
View Source Code in Full Screen
#------------------------------------------------------------ # Collections of Data #------------------------------------------------------------ # If you have a whole bunch of data that all represent different data points for the same thing, # it would be best to store that data in a collection of some sort. # Data collections are abstract data types rather than primitive. Lists, Tuples, Sets, and Dictionaries # are some of the collection types in Python. Each can store different types of data in one instance. print('''------------------------------------------------------------ Lists ------------------------------------------------------------''') # Lists are exactly what they sound like. They store data with an order, like a shopping list or a to-do list. # Create them by using the square brackets. list1 = [5, "Bob", "Hello", 2.7, 10] print("list1 =", list1) # In Python, you can store all different types of data within the same list, as shown above. # However, beware of logic errors that may arise when using a list containing different types. # Generally, if using a list, best practice would be to have all values be the same type. # For all collections of data, you can see if a value is in the collection by using the keyword 'in'. print( "Bob" in list1 ) # True print( 20 in list1 ) # False # Lists have indices too, just like strings. Remember how I said strings are lists of characters? They follow the same rules. # First item in the list is at index 0. The length of a list is the number of items in the list. # The last item in the list is at index len(list)-1, or -1. print("There are", len(list1), "items in the list.") print("First item =", list1[0]) print("Fourth item =", list1[3]) print("Last item =", list1[-1]) # Can change a value in the list using the index as well. list1[3] = 3.6 print('list1 =', list1) # Can create sublists by slicing the list, just like a string. # list[start:end], the value at the end index is not included in the sublist sublist1 = list1[1:3] print("sublist1 =", sublist1) sublist2 = list1[:3] # starts at 0 by default print("sublist2 =", sublist2) sublist3 = list1[2:] # goes to last value by default print("sublist3 =", sublist3) # You can also reverse a list using slicing, just like a string. reverse = list1[::-1] print("reverse =", reverse) print() # You can also have lists inside of lists, or multi-dimensional lists. mdlist = [ [90, 80, 70, 5], [10, 20, 30, 15], [50, 60, 40, 55] ] # Each list within the list is a ROW. Each item in the row is further indexed, we refer to the second index as the COLUMN index. # To access a value within a multi-dimensional list, you start from the outside and work your way in. # For a 2D List, you would use list[row][column] print("mdlist[0][0] =", mdlist[0][0]) # 90 print("mdlist[1][3] =", mdlist[1][3]) # 15 # Each inner list has a length as well. Since there are 3 rows, len(mdlist) = 3. print("There are", len(mdlist), "rows in mdlist.") # In the first row, there are 4 values. print("There are", len(mdlist[0]), "columns in the first row of mdlist.") # Need to add a new value to the end of the list? Use the append function. list1.append("Goodbye") print("list1 =", list1) # If you use append to add a list of items to another list, they will be added as one value (a list) list1.append([1, 9]) print("list1 =", list1) # If you want each individual value to be added to the list as separate items, use the extend function instead. list1.extend([3, 4]) print("list1 =", list1) # You can insert a value into the list at a specific index using the insert function. # It will insert it into the list such that the new value is at the specified index. # Every value at that index or greater is moved right by one index. list1.insert(2, 'A') print("list1 =",list1) print() # There are 3 ways to remove from a list: del, remove, and pop # del deletes the item at that index. All values at indices higher than this will move left by 1. del list1[7] print("list1 =", list1) # remove will remove a specific value from the list. However if the value is NOT in the list, this will cause an error list1.remove('Goodbye') print("list1 =", list1) # pop can be used in two different ways # If you call it with nothing in the parentheses it will remove the last item and return it. x = list1.pop() print("x =", x) print("list1 =", list1) # You can also call it by passing the index of the item to remove. # It will remove the item at that index from the list and return the value to you (so you can store and use it) y = list1.pop(2) print("y =", y) print("list1 =", list1) print() # There are 2 methods you can use to sort a list. # However, both of them need all of the items in the list to be the same type. list2 = [3, 5, 9, 7, 10, 8] # The built-in method sorted will sort the list and return it sorted, without changing the original list. sortedlist2 = sorted(list2) print("list2 =", list2) print("sortedlist2 =", list2) # Lists also have a sort function defined to sort them, but this will sort them "in place", meaning it changes the original list. list2.sort() print("list2.sort() =", list2) # You can find out how many times a specific value appears in a list using the count function. list3 = [2, 6, 5, 4, 6, 2, 6, 7] print("list3 =", list3) print("6 appears", list3.count(6), "times") # You can find the index where a value first occurs in a list using the index function. print("5 is located at index", list3.index(5)) print() print('''------------------------------------------------------------- Tuples -------------------------------------------------------------''') # Tuples are similar to lists, except you CANNOT change their individual values. # Create a tuple using parentheses. tuple1 = (5, 2, "Bob") print("tuple1 =", tuple1) # tuples are also indexed, so you can access each piece with the index print("First item in tuple1 =", tuple1[0]) # tuples also have a length print("There are", len(tuple1), "items in tuple1.") print() # However, you cannot change individual values of a tuple. # Uncomment the next line and you will see that it causes a TypeError: 'tuple' object does not support item assignment # tuple1[0] = 10 # If you need to change anything about the values in a tuple, you will have to create a new tuple, # copy over the values that remain the same, and change the ones needed to be changed in the new tuple. print('''-------------------------------------------------------------- Sets --------------------------------------------------------------''') # Sets are different than the other data collections we are discussing because they are NOT indexed, meaning there is no order. # Sets also do not allow duplicate values to be stored within them. Every value in a set is unique. # Use the curly brackets and list items separated by commas to create a set. set1 = {'birch', 'elm', 'fir'} print("set1 =", set1) # Every time you press the run button, the set above may print out in a different order than we defined it as. # To access individual values, you would need to use a loop and access all of the values at once. We'll look at this in a later lesson. # Use 'in' and 'not in' to check if a value exists already in a set. print('birch' in set1) # True since 'birch' is in the set print('birch' not in set1) # False since 'apple' is not in the set # Use the add function to add values to a set. # If the value is already in the set, then it will not be added and no error will occur. set1.add('apple') set1.add('birch') print("set1 =", set1) # If you need to add multiple items to the set, use the update function. set1.update(['cedar', 'cypress', 'ash']) print("set1 =", set1) # You can also view the number of items in a set using the len function. print("There are", len(set1), "items in set1.") # There are 2 ways to remove from the set: remove and discard # remove will remove the item from the set, but if it does not exist in the set, it will cause an error set1.remove('birch') print("set1 =", set1) # Uncomment the line below to see the error. #set1.remove('orange') # To avoid this error, use the discard function instead. If the item is in the set, it will remove it. # Otherwise, it will do nothing. set1.discard('apple') print("set1 =", set1) # properly removes 'apple' set1.discard('orange') # 'orange' is not in the set, but no error occurs print("set1 =", set1) # Want a random item in the set removed and returned? Use the pop function. However, if the set is empty, it will removed = set1.pop() print("removed =", removed) print("set1 =", set1) # You can clear all items from a set and change it to an empty set using the clear function set1.clear() print("set1 =", set1) print() # If you use the del keyword on the set, it will delete the variable altogether and no more operations can be done on the set # Uncomment the 2 lines below to see that it causes a NameError, since the variable set1 no longer exists. #del set1 #print("set1 =", set1) # Sets have many functions defined just for them to combine sets and create subsets. You can read more about those in the documentation. print('''-------------------------------------------------------------- Dictionaries --------------------------------------------------------------''') # Dictionaries store data in key-value pairs. Keys can be string literals, integer literals, float literals, or tuples. # Values can be any type, including collections of data like other dictionaries, sets, and lists. # You as the programmer determine the keys and set their values. # Dictionaries are great when you have a bunch of different TYPES of data, each representing a different part of one object. # It allows you to essentially define multiple variables for each property without creating individual variables # and still know which values represent that object. # Create a dictionary using the curly brackets. Inside, write the key, followed by a colon, then the value and a comma. # So long as there is another value to be added to the dictionary, the value before it should have a comma at the end, like a list. square = { 'x': 200, 'y': 150, 'color': 'red', 'side': 50 } print("square =", square) # The keys of a dictionary allow it to be indexed, like a list. # However, in a dictionary, the index is the key, which is not necessarily an integer. print( square['x'] ) # 200 print( square['color'] ) # red # If you try to access a key that does not exist, you will get an error. # To avoid this error, you can use the get() function instead: print( square.get('x') ) # 'name' is not in the dictionary, so trying to access it with [] would cause KeyError # using the get() function, it will return None instead print( square.get('name') ) # Just like lists, you can change the value stored to a key the same way. square['x'] = 100 print("square =", square) # Just like any other set, you can check if a KEY is in the dictionary using the 'in' keyword. print( 'color' in square ) # True print( 'name' in square ) # False print( 'name' not in square ) # True # If you want to know all the keys in a dictionary, use the keys() function print( square.keys() ) # This will return a dict_keys object. To use it as a list, you would need to change its type to a list using the list() function print("Keys:", list(square.keys()) ) # Want a list of values? Use the values() function. It returns a dict_values object, so change its type to a list print("Values:", list(square.values()) ) # Want a list containing all key-value pairs? Use the items() function # This function will return a dict_items object, where each item is represented as a tuple (key, value) print("Items:", list(square.items()) ) # Want to add a new key-value pair to the dictionary? Just set its value as if it was already in the dictionary. square['name'] = 'Bob' print("square =", square) # Want to add or update multiple key-value pairs in the dictionary? Use the update function and pass in another dictionary square.update({ 'x': 50, 'color': 'orange', 'outline': 'blue' }) print("square =", square) # Remove a key-value pair from the dictionary using the pop function. square.pop('name') print("square =", square) # Clear all key-value pairs from a dictionary using the clear function square.clear() print("square =", square) print("\n") # Just like with lists, you can have multiple layers in a dictionary. Let's take a look at an example and how to access them person = { 'name': 'Bob', 'age': 23, 'job': 'Student', 'pets': [ { 'name': 'Spot', 'age': 4, 'type': 'dog' }, { 'name': 'Salem', 'age': 12, 'type': 'cat' } ] } # to print the person's name, we would write print( person['name'] ) # But how about if we wanted to know something about the pets? # What if we wanted the name of his second pet? print( person['pets'] ) # this will give the whole list of pets print() print( person['pets'][1] ) # this will give the item at index 1 in the pets list, which is the second pet in the list print() # since person['pets'][1] is a dictionary, to get the pet's name, we would then need to access the 'name' key for that pet print( person['pets'][1]['name'] ) # this will give us the second pet's name
CS110_L3_Notes.py
( around 261 lines Python3 code )
Published By:
Mentor Sabrina
Created on
2020-10-21T16:45:21Z
Python3 Editor
- an
OYOclass
application,
own your own class today
.
Run
Result
Status:
Program is not running