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.

As the last example in this interaction demonstrates, we can even assign nestedsequences, and <strong>Python</strong> unpacks their parts according to their shape, as expected. Inthis case, we are assigning a tuple of two items, where the first item is a nestedsequence (a string) exactly as though we had coded it this way:>>> ((a, b), c) = ('SP', 'AM') # Paired up by shape and position>>> a, b, c('S', 'P', 'AM')<strong>Python</strong> pairs the first string on the right ('SP') with the first tuple on the left ((a, b)),and assigns one character at a time, before assigning the entire second string ('AM')to the variable c all at once. In this event, the sequence-nesting shape of the object onthe left must match that of the object on the right. Nested sequence assignment likethis is somewhat advanced, and rare to see, but it can be convenient for picking outthe parts of data structures with known shapes. For example, this technique alsoworks in function argument lists because function arguments are passed by assignment(as we’ll see in the next part of the book).Sequence-unpacking assignments also give rise to another common coding idiom in<strong>Python</strong>—assigning an integer series to a set of variables:>>> red, green, blue = range(3)>>> red, blue(0, 2)This initializes the three names to the integer codes 0, 1, and 2, respectively (it’s<strong>Python</strong>’s equivalent of the enumerated data types you may have seen in other languages).To make sense of this, you need to know that the range built-in functiongenerates a list of successive integers:>>> range(3) # Try list(range(3)) in <strong>Python</strong> 3.0[0, 1, 2]Because range is commonly used in for loops, we’ll say more about it in Chapter 13.Another place you may see a tuple assignment at work is for splitting a sequence intoits front and the rest in loops like this:>>> L = [1, 2, 3, 4]>>> while L:... front, L = L[0], L[1:]... print front, L...1 [2, 3, 4]2 [3, 4]3 [4]4 []The tuple assignment in the loop here could be coded as the following two linesinstead, but it’s often more convenient to string them together:... front = L[0]... L = L[1:]Assignment Statements | 221

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

Saved successfully!

Ooh no, something went wrong!