12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

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

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

L += [9, 10] # Mapped to L.extend([9, 10])>>> L[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Augmented assignment and shared referencesThis behavior is usually what we want, but notice that it implies the += is an in-placechange for lists; thus, it is not exactly like + concatenation, which always makes anew object. As for all shared reference cases, the difference might matter if othernames reference the object being changed:>>> L = [1, 2]>>> M = L # L and M reference the same object>>> L = L + [3, 4] # Concatenation makes a new object>>> L, M # Changes L but not M([1, 2, 3, 4], [1, 2])>>> L = [1, 2]>>> M = L>>> L += [3, 4] # But += really means extend>>> L, M # M sees the in-place change too!([1, 2, 3, 4], [1, 2, 3, 4])This only matters for mutables like lists and dictionaries, and it is a fairly obscurecase (at least, until it impacts your code!). As always, make copies of your mutableobjects if you need to break the shared reference structure.Variable Name RulesNow that we’ve explored assignment statements, it’s time to get more formal aboutthe use of variable names. In <strong>Python</strong>, names come into existence when you assignvalues to them, but there are a few rules to follow when picking names for things inyour programs:Syntax: (underscore or letter) + (any number of letters, digits, or underscores)Variable names must start with an underscore or letter, which can be followedby any number of letters, digits, or underscores. _spam, spam, and Spam_1 are legalnames, but 1_Spam, spam$, and @#! are not.Case matters: SPAM is not the same as spam<strong>Python</strong> always pays attention to case in programs, both in names you create, andin reserved words. For instance, the names X and x refer to two different variables.For portability, case also matters in the names of imported module files,even on platforms where the filesystems are case insensitive.Assignment Statements | 225

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

Saved successfully!

Ooh no, something went wrong!