#!/usr/bin/env python # coding: utf-8 # # Tuples # Open In Colab # # - http://openbookproject.net/thinkcs/python/english3e/tuples.html # - containers used for grouping data values surrounded with parenthesis # - data values in tuples are called elements/items/members # - two major operations done with tuples are: # 1. packing (creating tuples) # 2. unpacking (storing data into individual variables) # In[1]: year_born = ("Paris Hilton", 1981) # tuple packing # In[2]: print(year_born) # In[11]: star = "Paris", 'J', 'Hilton', 1981, 32, 1.2 # tuple packing # In[12]: star # In[13]: type(star) # In[14]: # tuple assignment fname, mi, lname, year, age, income = star # tuple unpacking; # no. of variables must match no. tuple values # In[9]: fname # In[10]: lname # In[11]: print(income) # In[12]: # swap values of two variables a = 100 b = 200 a, b = b, a # In[13]: print(a, b) # ## Member access # - each member of tuple can be accessed using [ index ] operator # - index is 0 based or starts from 0 # In[1]: name = ('John', 'A.', 'Smith') # In[3]: print(name[0], name[1], name[2]) # ## len built-in function # - gives the length (no. of elements) of tuple # In[4]: len(name) # ## Tuple membership # - **in** and **not in** boolean operators let's you check for membership # In[7]: 'John' in name # In[8]: 'B.' in name # In[9]: 'Jake' not in name # ## Tuples can be returned from a function # In[29]: def maxAndMin(a, b, c, d, e): myMax = a #max(a, b, c, d, e) if myMax < b: myMax = b if myMax < c: myMax = c if myMax < d: myMax = d if myMax < e: myMax = e values = [a, b, c, d, e] myMin = min(values) return (myMax, myMin) # In[30]: ab = maxAndMin(10, 20, 5, 100, 34) print('max =', ab[0], 'min=', ab[1]) # ## Tuples are immutable # - can't change tuple in-place or update its elements similar to string # In[5]: a = (1, 2, 3) print(a[0]) # In[6]: a[0] = 100