1 / 21

COMPSCI 101 S1 2014 Principles of Programming

COMPSCI 101 S1 2014 Principles of Programming. Tuples. Learning outcomes. At the end of this lecture, students should be able to: understand the tuples create tuples assign values using tuples return tuples know the differences between tuples and lists Examples & Exercises

santa
Download Presentation

COMPSCI 101 S1 2014 Principles of Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMPSCI 101 S1 2014Principles of Programming Tuples

  2. Learning outcomes • At the end of this lecture, students should be able to: • understand the tuples • create tuples • assign values using tuples • return tuples • know the differences between tuples and lists • Examples & Exercises • Exercise 1: Returns the min and max in a list • Exercise 2: A phonebook application • References: • Tuples • https://docs.python.org/3.3/tutorial/datastructures.html#tuples-and-sequences COMPSCI101

  3. Introduction • Data structures • Structures that hold and organize information • Python comes with a general set of built in data structures: • lists • tuples • strings • dictionaries • others... COMPSCI101

  4. Creating Sequences • Strings • Use quotes • string1 = "" • Lists • Use brackets • Separate multiple items with a comma • list1 = [] • Tuples • Use parentheses • Separate multiple items with a comma • tuple1 = () COMPSCI101

  5. Creating Tuples • Create a tuple by enclosing its elements inside a pair of parentheses. The elements are separated by commas. • Create an empty tuple • Create a tuple with three elements t1 = () print (t1) print (type(t1)) () <class 'tuple'> t2 = (1, 2, 3) print (t2) print (type(t2)) (1, 2, 3) <class 'tuple'> COMPSCI101

  6. Commas make a tuple • For tuples, you can think of a comma as the operator that makes a tuple, where the ( ) simply acts as a grouping: • Example: • However, look at the following example • Create a tuple with a SINGLE element: t3 = 1,2 print (t3) print (type(t3)) t3 = (1,2) (1, 2) <class 'tuple'> t4 = (1) print (t4) print (type(t4)) 1 <class 'int'> Integer Type t5 = 1, print (t5) print (type(t5)) t5 = (1,) (1,) <class 'tuple'> COMPSCI101

  7. Creating Tuples Using the “tuple” function • Another way to create a tuple is using the built-in function “tuple” • With no argument, it creates an empty tuple • Create a tuple from a string • A tuple with the elements of the sequence • Note: because tuple is the name of a built-in function, you should avoid using it as a variable name. t6 = tuple() print (t6) print (type(t6)) () <class 'tuple'> t7 = tuple("abcdef") print (t7) print (type(t7)) ('a', 'b', 'c', 'd', 'e', 'f') <class 'tuple'> COMPSCI101

  8. Tuples and Lists Demo 1 • A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets. • The elements of a tuple have a defined order, just like a list. • Tuple indices are zero-based, just like a list, so the first element of a non-empty tuple is always t[0]. • Negative indices count from the end of the tuple, just as with a list. a f print (t7[0]) print (t7[-1]) COMPSCI101

  9. Slicing • Slicing works too, just like a list. • Note that when you slice a list, you get a new list. when you slice a tuple, you get a new tuple. • Using positive indices: • Contains all the elements of the tuple, in order, starting with the first slice index, up to but not including the second slice index • Using negative indices: • Reading the tuple from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don't want. t8 = t7[2:4] print (t8) print (type(t8)) ('c', 'd') <class 'tuple'> ('d', 'e') t9 = t7[-3:-1] print (t9) COMPSCI101

  10. Immutable lists • Tuples are simply immutable lists. Once they are created, their contents cannot be changed. • i.e. if you try to modify one of the elements of the tuple, you get an error: • You can’t modify the elements of a tuple, but you can replace one tuple with another: 'tuple' object does not support item assignment t7[0] = 1 'tuple' object has no attribute 'append' t7.append('A') ('A', 'b', 'c', 'd', 'e', 'f') t10 = ('A',) + t7[1:] print (t10) COMPSCI101

  11. Operators: +, * t2 t5 • Combine two tuples • Duplicate a tuple (1, 2, 3, 1) t12 = t2 + t5 print (t12) (1, 2, 3, 1, 2, 3) t11 = t2 * 2 print (t11) COMPSCI101

  12. Operations t11 • The common operations for sequences can be used for Tuples: • len, min, max, and sum • “in” and “not in” operators can be used to determine whether an element is in a tuple length is 6 max is 3 min is 1 sum is 12 print ("length is", len(t11)) print ("max is", max(t11)) print ("min is", min(t11)) print ("sum is", sum(t11)) True False print (2 in t11) print (10 in t11) COMPSCI101

  13. Tuples as return values • A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values! • Examples: • The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder t = divmod(7, 3) print (t) (2, 1) COMPSCI101

  14. Exercise 1 Demo 1 • Task: • Complete the min_max()function which returns the minimum and the maximum number of a list in a tuple. • Arguments: numbers (a list) • Returns: a tuple (min, max) • Example: (-2, 4) min_max([2,4,2,1,-2]) COMPSCI101

  15. Tuple assignment • Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment. • This allows you to assign more than one variable at a time when the left hand side is a sequence. • In Python, we have the concepts of packing and unpacking when using tuples. • In packing, we place values into a new tuple. • And in unpacking we extract those values back into variables. pair = ("dog", "cat") (key, value) = pair print(key) print(value) dog cat COMPSCI101

  16. Swapping Values • With conventional assignments, you have to use a temporary variable. For example, to swap a and b: • Using tuple assignment to swap values: • Note: Each value is assigned to its respective variable. • The number of variables on the left and the number of values on the right have to be the same: temp = a a = b b = temp a, b = b, a ValueError: too many values to unpack a, b = 1, 2, 3 COMPSCI101

  17. Case Study 1Create a phonebook dictionary V2 • Task: • Complete the create_phonebook()function which takes a filename as a parameter and builds a phonebook dictionary. You may assume that the text has no punctuation; and keys and values are separated by whitespace. • In the dictionary, the tuples containing first name and surname of individuals (the keys) are mapped to strings containing phone numbers (the values). • Arguments: a filename • Prints: a phonebook dictionary • Example: Angela Chang 3737599-85654 Ann Cameron 3737599-84947 Patricia Riddle 3737599-87093 Andrew Luxton-Reilly 3737599-85654 my_phonebook = create_phonebook("phonebook.txt") COMPSCI101

  18. Case Study 1Algorithm Demo 2 COMPSCI101

  19. Case Study 2Phonebook Lookup Application V2 • Task: • Complete the lookup() function which takes a phonebook dictionary as a parameter. In the dictionary, the tuples containing first name and surname of individuals (the keys) are mapped to strings containing phone numbers (the values). Your function should provide a simple user interface through which a user can enter the first name and surname of an individual and obtain the phone number assigned. • Arguments: phonebook dictionary • Prints: phone number of an individual • Example: The dictionary phonebook >>> lookup({('Ann', 'Cameron'): '3737599-84947', ('Patricia', 'Riddle'): '3737599-87093', ('Andrew', 'Luxton-Reilly'): '3737599-85654', ('Angela', 'Chang'): '3737599-85654'}) COMPSCI101

  20. Case Study 2Algorithm Demo 2 COMPSCI101

  21. Summary • Tuples are like lists except they are immutable. Once they are created, their contents cannot be changed. • If the contents of a list in your application do not change, you should use a tuple to prevent data from being modified accidentally. • Tuples are more efficient than lists. • Lists • Not restricted to values of the same type • Programmers usually use lists to hold data that is of the same type • Tuples • Used to contain data that is related but not necessarily of the same type COMPSCI101

More Related