Python Data Structures LN_5_DataStructures PDF

Summary

These lecture notes describe Python data structures, including Lists, Tuples, Dictionaries, and Sets. The notes cover various operations on these data structures, such as adding, modifying, and accessing data elements.

Full Transcript

TK2053 PROGRAMMING PARADIGM Script Programming with Python - Data Structures 2 Object Recall (Lecture slide 3): An object is an entity that has a type, such as string or integer Determines what can be done with the data Ex...

TK2053 PROGRAMMING PARADIGM Script Programming with Python - Data Structures 2 Object Recall (Lecture slide 3): An object is an entity that has a type, such as string or integer Determines what can be done with the data Example the object has the type int, it can be added to another int. Determines if the data value can be changed (mutable) or is constant (immutable) 3 Object Dynamically typed keeps track of types for you automatically instead of requiring declaration code Strongly typed : type of an object does not change, even if its value is mutable Fundamentals of Python: From First Programs Through Data Structures 4 Mutable vs Immutable Think of an object as a box Mutable An open box, not only can we see the value inside, we can also change it. BUT we can not change its type. Immutable A closed box with a clear window, we can see the value but we can not change it. When value change, Python will designate a new memory location to hold the new value Variable will reference that new object Introducing Python, O’Reilly Media, page 16 5 Mutable vs Immutable Source: Mutable vs Immutable Objects in Python, https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747 6 Mutable vs Immutable List Integer String Tuple Fundamentals of Python: From First Programs Through Data Structures 7 Mutable vs Immutable Fundamentals of Python: From First Programs Through Data Structures 8 List A list is an ordered sequence of Python objects Objects can be of any type Objects do not have to all be the same type. * If you need to keep track of unique values and do not care about order, use set. 9 List – Creating a list Can be made with zero or more elements, separated by commas Create with [] Does not need to be unique Create an empty list with list() 10 List – Convert other Data Types to List list() can be used to convert other data types to lists. split() can be used to chop a string into a list of substrings *to combine, use join() 11 List – Extracting Item To extract a single value from a list, we can specify its offset 12 List –Modifying Item To modify a single value from a list by its offset Since lists are mutable objects, fruits_2 will points to the same memory location as fruits_1. Any changes of values in fruits_2 will be reflected in fruits_1 as well. 13 List –Modifying Item To ensure values in the original list is unchanged Besides list() conversion function, we can also use the - The list copy() function - The list slice[:] to have an independent fresh list. 14 List – Using Slice Just like string, we can extract a subsequence of a list by using a slice 15 List – Nested List List can contain elements of different types, including other lists 16 List – Operations Example of additional list operations 17 List – Operations Example of additional list operations 18 Tuples Tuples (similar to lists), are sequences of arbitrary items. Difference with lists, tuples are immutable Can not add, delete or change items after the tuple is defined 19 Tuples – Creating a Tuple To create an empty tuples To create a tuple with one or more elements You do not need parentheses when creating tuple – it is the trailing commas that define a tuple. However using parentheses to enclose value can be useful to help make tuple more visible. tuple() conversion function can make tuples from other objects 20 Tuples – Creating a Tuple To assign multiple variables to elements of tuple (i.e. tuple unpacking) Using tuple to exchange values in one statement 21 Tuples vs Lists We can always use tuple in place of lists, but they have fewer functions (i.e. no append(), insert() and etc. because they are immutable) - Tuple use less space - Can not clobber tuple items by mistake - Can use tuples as dictionary keys (see next section) 22 Dictionaries Dictionary (similar to lists), but The order of items does not matter Elements in dictionary can not be selected by an offset. Need to specify unique key. The key is often a string, but can be any immutable types (i.e. Boolean, integer, float, tuple, and etc.) Dictionaries are mutable, so we can add, delete and change their key-value elements. 23 Dictionaries – creating a dict To create a dictionary, place curly brackets ({ }) around comma- separated key:value pairs Empty dictionary with no keys or values A dictionary with key:value pairs 24 Dictionaries – Convert to dict Can use dict() function to convert two-value sequences (lists or tuples) into a dictionary 25 Dictionaries – Add or Change item Adding an item to a dictionary is easy. Just refer to the item by its key and assign a value. * Note that dictionary keys must be unique. 26 Dictionaries – Add or Change item To change an item in the dictionary By using the same key (‘Gilliam’), we replace the original value ‘Gerry’ with ‘Terry’. 27 Dictionaries – Get an item by [key] This is them most common use of a dictionary. We specify the dictionary and key to get the corresponding value 28 Dictionaries – Get an item by [key] This is them most common use of a dictionary. We specify the dictionary and key to get the corresponding value If the key is not present, you will get an exception. To avoid this, always check the availability of the key 29 Dictionaries – Get an item by [key] To prevent exception, can also use special dictionary get() function 30 Dictionaries – Get all keys or values Use keys() to get all keys and values() to get all values in a dictionary 31 Dictionaries – Get all key-Value Pairs Use items() function to get all key-value pairs 32 Set Set (similar to dictionaries), but with its values thrown away leaving only the keys. The keys for set must be unique. Same concept in Discrete Mathematics 33 Set – Create a Set To create a set, we can use the set() function or enclose one or more comma-separated values in curly brackets 34 Set – Convert to Set We can create a set from list, string, tuple or dictionary, discarding any duplicate values 35 Set – Test for Value Example: Given a dictionary called drinks Which drinks contain vodka? Output: 36 Set – Test for Value Example: Given a dictionary called drinks Which drinks contain vodka but no vermouth and cream? Output: 37 Set – Test for Value Example: Given a dictionary called drinks To save the ingredient sets for drink in variable, 38 Set – Set Operators Given a test sets Intersection of the set with special punctuation symbol & or the set intersection() function 39 Set – Set Operators Given a test sets Union of the set by using | or the set union() function 40 Set – Set Operators Given a test sets Difference of the set by using - or the set difference() function 41 Set – Set Operators Besides the common set operations (i.e. union, intersection and difference), the less common operations are Exclusive or using ^ or symmetric_difference() Subset of another set by using = or issuperset() Proper superset by using > *A superset is the opposite of a subset (all members of the second set are also members of the first). 42 Compare Data Structures Review on creating list, tuple, dictionary For the list and tuple, the value between the square brackets is an integer offset. For the dictionary, it’s a key. For all three, the result is a value. 43 Bigger Data Structures Given 3 lists Make a tuple containing the lists Or make a list containing the lists Or dictionary of lists (* keys need to be immutable) 44 Hands-on Activities Store the names of a few of your friends in a list called names. Print a message to them. The text of each message should be the same but each message should be personalized with the person’s name. Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary.

Use Quizgecko on...
Browser
Browser