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.

10.12. Listarguments 97The statediagram looks likethis:ab[ 1, 2, 3 ]The association of a variable with an object is called a reference. In this example, there are tworeferences tothesame object.Anobjectwithmorethanonereferencehasmorethanonename,sowesaythattheobjectisaliased.Ifthealiased object ismutable, changes made withone alias affect the other:>>> b[0] = 17>>> print a[17, 2, 3]Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing whenyou are working withmutable objects.For immutable objects likestrings,aliasing isnot as much ofaproblem. Inthisexample:a = 'banana'b = 'banana'Italmost never makes adifference whetheraandbrefertothe samestringor not.10.12 ListargumentsWhen you pass a list to a function, the function gets a reference to the list. If the function modifiesa list parameter, the caller sees the change. For example, delete_head removes the first elementfrom alist:def delete_head(t):del t[0]Here’s how itisused:>>> letters = ['a', 'b', 'c']>>> delete_head(letters)>>> print letters['b', 'c']The parameter t and the variable letters are aliases for the same object. The stack diagram lookslikethis:__main__letterslist0’a’delete_headt12’b’’c’

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

Saved successfully!

Ooh no, something went wrong!