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.

96 Chapter 10. Listsa = 'banana'b = 'banana'Weknowthataandbbothrefertoastring,butwedon’tknowwhethertheyrefertothesamestring.There aretwo possiblestates:ab’banana’’banana’ab’banana’In one case,aandbrefer to two different objects that have the same value. In the second case, theyrefer tothe sameobject.To check whether twovariables refertothe sameobject, you can use theisoperator.>>> a = 'banana'>>> b = 'banana'>>> a is bTrueInthisexample, <strong>Python</strong> only created one stringobject, and bothaandbrefertoit.But when you create twolists,you get two objects:>>> a = [1, 2, 3]>>> b = [1, 2, 3]>>> a is bFalseSo thestatediagram looks likethis:ab[ 1, 2, 3 ][ 1, 2, 3 ]In this case we would say that the two lists are equivalent, because they have the same elements,but not identical, because they are not the same object. If two objects are identical, they are alsoequivalent, but ifthey are equivalent, they arenot necessarily identical.Until now, we have been using “object” and “value” interchangeably, but it is more precise to saythat an object has a value. If you execute [1,2,3], you get a list object whose value is a sequenceofintegers. Ifanotherlisthasthesameelements,wesayithasthesamevalue,butitisnotthesameobject.10.11 AliasingIfareferstoan object and you assignb = a,then both variables refertothe sameobject:>>> a = [1, 2, 3]>>> b = a>>> b is aTrue

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

Saved successfully!

Ooh no, something went wrong!