class: big, middle # Engineering 1020: Introduction to Programming .title[ .lecture[Lecture \20\:] .title[Tuples] ] .footer[[/lecture/20/](/lecture/20/)] --- # Recall: ### Objects ### Methods ### Common methods of: * `list` * `str` --- # Tuples ### You've heard these before? -- .floatleft[ * quadruple * quintuple * sextuple * septuple ] -- .floatright[ ### Mathematically: ## $n$-tuple ] --- # Python tuple -- ### An ordered collection -- So... what's different about this vs a list? -- ### An _immutable_ ordered collection -- ```python l = [1, 2, 3] t = (1, 2, 3) l[1] = 42 t[1] = 42 ``` --- # Where do we use tuples? -- ### Storing simple sequences -- ### Returning multiple things from functions -- * let's write a `divide(num, denom)` function! -- * other functions you might bump into --- # More tuple syntax ### Single-element tuples: -- ```python x = (1,) ``` -- ### *Destructuring* tuples: -- ```python p = get_a_cartesian_point() x, y = p # or just: x, y = get_a_cartesian_point() ``` -- Helpful for explicitly stating expected number of elements! --- # matplotlib example ```python >>> help(plt.subplots) Help on function subplots in module matplotlib.pyplot: subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw= None, gridspec_kw=None, **fig_kw) Create a figure and a set of subplots This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call. [...] Returns ------- fig : :class:`matplotlib.figure.Figure` object ax : Axes object or array of Axes objects. [...] ``` ??? Returns **two** values: **`fig` and `ax`** --- # Using subplots <img src="covid.png" align="right" height="350"/> .footnote[ Data: http://bit.ly/covid19-nl Code: https://gist.github.com/trombonehero/b7b2ec2667dab2bf3bb09399984a8046 ] ```python fig, ax = plt.subplots(2, # ... fig.suptitle('COVID-19 cases in # ... ax[0].set_title('New and total cases') ax[0].plot(total) ax[0].plot(new) ax[0].legend(['Total', 'New']) ax[1].set_title('Total cases by category') ax[1].stackplot(range(len(total)), deaths, # ... ax[1].legend(['Deceased', 'Recovered', # ... plt.show() ``` --- # Using tuples ### Just like lists: -- * iteration -- * `count()` method -- * `index()` method -- * ... but that's all! --- # Argument tuples ### Slightly more advanced usage -- ```python def foo(*args): for a in args: print(a) foo(1, 2, 3) ``` -- ### Or even: ```python def multiply(x, y): return x * y t = (1, 2) result = multiply(*t) ``` --- # Summary ### Tuples * simple ordered _immutable_ collections * syntax * usage --- class: big, middle (here endeth the lesson)