12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

116 Chapter 12. TuplesBecausetupleisthename of abuilt-infunction, you should avoid using itas avariable name.Most listoperators alsoworkon tuples. The bracket operator indexes an element:>>> t = ('a', 'b', 'c', 'd', 'e')>>> print t[0]'a'And thesliceoperator selects arange ofelements.>>> print t[1:3]('b', 'c')But ifyou trytomodify one of theelements of thetuple, you get an error:>>> t[0] = 'A'TypeError: object doesn't support item assignmentYou can’t modifythe elements of atuple, but you can replace one tuplewithanother:>>> t = ('A',) + t[1:]>>> print t('A', 'b', 'c', 'd', 'e')12.2 Tuple assignmentIt is often useful to swap the values of two variables. With conventional assignments, you have touseatemporary variable. For example, toswapaandb:>>> temp = a>>> a = b>>> b = tempThis solutioniscumbersome; tuple assignment ismoreelegant:>>> a, b = b, aThe left side is a tuple of variables; the right side is a tuple of expressions. Each value is assignedto its respective variable. All the expressions on the right side are evaluated before any of theassignments.The number ofvariables onthe leftand the number of values on theright have tobe thesame:>>> a, b = 1, 2, 3ValueError: too many values to unpackMore generally, the right side can be any kind of sequence (string, list or tuple). For example, tosplitan email address intoauser name and a domain, you could write:>>> addr = 'monty@python.org'>>> uname, domain = addr.split('@')The return value from split is a list with two elements; the first element is assigned to uname, thesecond todomain.

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

Saved successfully!

Ooh no, something went wrong!