12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

118 Chapter 12. Tuples>>> t = (7, 3)>>> divmod(t)TypeError: divmod expected 2 arguments, got 1But ifyou scatterthe tuple, itworks:>>> divmod(*t)(2, 1)Exercise 12.1 Many of the built-in functions use variable-length argument tuples. For example,maxandmincan take any number of arguments:>>> max(1,2,3)3Butsumdoes not.>>> sum(1,2,3)TypeError: sum expected at most 2 arguments, got 3Writeafunction calledsumallthat takes any number of arguments and returns theirsum.12.5 Listsand tupleszip is a built-in function that takes two or more sequences and “zips” them into a list 1 of tupleswhere each tuplecontains one element from each sequence.This example zips a stringand alist:>>> s = 'abc'>>> t = [0, 1, 2]>>> zip(s, t)[('a', 0), ('b', 1), ('c', 2)]Theresultisalistoftupleswhereeachtuplecontainsacharacterfromthestringandthecorrespondingelementfromthe list.Ifthesequences arenot the samelength, the resulthas the length of theshorter one.>>> zip('Anne', 'Elk')[('A', 'E'), ('n', 'l'), ('n', 'k')]You can use tupleassignment inaforloop totraversealistof tuples:t = [('a', 0), ('b', 1), ('c', 2)]for letter, number in t:print number, letterEach time through the loop, <strong>Python</strong> selects the next tuple in the list and assigns the elements toletterandnumber. The output ofthis loop is:0 a1 b2 c1 In<strong>Python</strong>3.0,zipreturns aniterator oftuples, but formost purposes, aniterator behaves like alist.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!