Labels

Monday, August 22, 2011

Learning Python 3rd edition--1

1.    Python Object Types

Python is dynamically typed (it keeps track of types for you automatically instead of requiring declaration code), but it is also strongly typed (you can only perform on an object operations that are valid for its type).

Every object in Python is classified as immutable (unchangeable) or not. In terms of the core types, numbers, strings, and tuples are immutable; lists and dictionaries are not (they can be changed in-place freely). Among other things, immutability can be used to guarantee that an object remains constant throughout your program.

1.1      String


S # A 4-character string

'Spam'

>>> S[1:3] # Slice of S from offsets 1 through 2 (not 3)

'pa'

Their general form, X[I:J], means “give me everything in X from offset I up to but not including offset J.” The result is returned in a new object. In a slice, the left bound defaults to zero, and the right bound defaults to the length of the sequence being sliced. This leads to some common usage variations:

>>> S[1:] # Everything past the first (1:len(S))

'pam'

>>> S # S itself hasn't changed

'Spam'

>>> S[0:3] # Everything but the last

'Spa'

>>> S[:3] # Same as S[0:3]

'Spa'

>>> S[:-1] # Everything but the last again, but simpler (0:-1)

'Spa'

>>> S[:] # All of S as a top-level copy (0:len(S))

'Spam'



Finally, as sequences, strings also support concatenation with the plus sign (joining two strings into a new string), and repetition (making a new string by repeating another):

>>> S

'Spam'

>>> S + 'xyz' # Concatenation

'Spamxyz'

>>> S # S is unchanged

'Spam'

>>> S * 8 # Repetition

'SpamSpamSpamSpamSpamSpamSpamSpam'

1.2      List


lists support all the sequence operations we discussed for strings; the only difference is that results are usually lists instead of strings. For instance, given a three-item list:

>>> L = [123, 'spam', 1.23] # A list of three different-type objects

>>> len(L) # Number of items in the list

3

we can index, slice, and so on, just as for strings:

>>> L[0] # Indexing by position

123

>>> L[:-1] # Slicing a list returns a new list

[123, 'spam']

>>> L + [4, 5, 6] # Concatenation makes a new list too

[123, 'spam', 1.23, 4, 5, 6]

>>> L # We're not changing the original list

[123, 'spam', 1.23]



List Comprehensions

In addition to sequence operations and list methods, Python includes a more

advanced operation known as a list comprehension expression, which turns out to be

a powerful way to process structures like our matrix. Suppose, for instance, that we

need to extract the second column of our sample matrix. It’s easy to grab rows by

simple indexing because the matrix is stored by rows, but it’s almost as easy to get a

column with a list comprehension:

>>> col2 = [row[1] for row in M] # Collect the items in column 2

>>> col2

[2, 5, 8]

>>> M # The matrix is unchanged

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

List comprehensions derive from set notation; they are a way to build a new list by running an expression on each item in a sequence, one at a time, from left to right. List comprehensions are coded in square brackets (to tip you off to the fact that they make a list), and are composed of an expression and a looping construct that share a variable name (row, here). The preceding list comprehension means basically what it says: “Give me row[1] for each row in matrix M, in a new list.”

List comprehensions can be more complex in practice:

>>> [row[1] + 1 for row in M] # Add 1 to each item in column 2

[3, 6, 9]

>>> [row[1] for row in M if row[1] % 2 == 0] # Filter out odd items

[2, 8]

1.3      Dictionaries


Dictionaries, the only mapping type in Python’s core objects set, are also mutable: they may be changed in-place, and can grow and shrink on demand, like lists.

dictionaries are not sequences, they don’t maintain any dependable left-to-right order. This means that if we make a dictionary, and print it back, its keys may come back in a different order than how we typed them:

>>> D = {'a': 1, 'b': 2, 'c': 3}

>>> D

{'a': 1, 'c': 3, 'b': 2}

·       if we do need to impose an ordering on a dictionary’s items?

One common solution is to grab a list of keys with the dictionary keys method, sort that with the list sort method, and then step through the result with a Python for loop:

1.4      Tuple


(1,2,3,4)

They are immutable sequences. Tuples are not generally used as often as lists in practice, but their immutability is the whole point. If you pass a collection of objects around your program as a list, it can be changed anywhere; if you use a tuple, it cannot.

1.5      Files


A file’s contents are always a string of bytes to your script, regardless of the type of data the file contains.

No comments:

Post a Comment