12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

Let’s look at an example of nesting. The following interaction defines a tree of nestedcompound sequence objects, shown in Figure 9-1. To access its components, youmay include as many index operations as required. <strong>Python</strong> evaluates the indexesfrom left to right, and fetches a reference to a more deeply nested object at each step.Figure 9-1 may be a pathologically complicated data structure, but it illustrates thesyntax used to access nested objects in general:>>> L = ['abc', [(1, 2), ([3], 4)], 5]>>> L[1][(1, 2), ([3], 4)]>>> L[1][1]([3], 4)>>> L[1][1][0][3]>>> L[1][1][0][0]3[0] [1] [2][0] [1]abc 5[0] [1] [0] [1]1 2[0]43Figure 9-1. A nested object tree with the offsets of its components, created by running the literalexpression [‘abc’, [(1, 2), ([3], 4)], 5]. Syntactically nested objects are internally represented asreferences (i.e., pointers) to separate pieces of memory.References Versus CopiesChapter 6 mentioned that assignments always store references to objects, not copiesof those objects. In practice, this is usually what you want. Because assignments cangenerate multiple references to the same object, though, it’s important to be awarethat changing a mutable object in-place may affect other references to the sameobject elsewhere in your program. If you don’t want such behavior, you’ll need totell <strong>Python</strong> to copy the object explicitly.184 | Chapter 9: Tuples, Files, and Everything Else

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

Saved successfully!

Ooh no, something went wrong!