Wednesday, July 6, 2011

Python 2.7 study notes - part 1

I've established a habit to take notes when studying a new language or framework. This habit 'forced' me to extract essential knowledge from study materials, and compile them into notes which can be used as a cheat sheet for review.

Lately, I found more of my friends expressed their interests in learning Python. Python is certainly gaining attentions ... at least in my circle (PHP or Java developers). I thought to myself 'hmm, why not share my notes with my friends, or even post it in blog?'. So here it is. This note is not meant to be comprehensive. For a full Python tutorial, I recommend the book 'Dive into Python'.

Get help

# List attributes of an object

# Print doc string
print something.__doc__

What is False

None, 0, empty string, empty list, empty tuple, and empty dictionary are false.


d = {'firstname': 'david', 'lastname': 'cai'}

# ['firstname', 'lastname']

# ['david', 'cai']

# [('firstname', 'david'), ('lastname', 'cai')]

A list of keys returned by the keys method is not in order.
The values method returns a list of values in the same order as the list returned by the keys method.
The items method returns a list of tuples in the same order as the list returned by the keys method. The tuple is consisted of key and value.

Delete an item:

d = {'firstname': 'david', 'lastname': 'cai', 99: 'something'}

del d[99] 
# {'firstname': 'david', 'lastname': 'cai'}

# {}

del deletes an entry in dictionary by key. clear deletes all entries.



l = ['first', 'second', 'third', 'fourth', 'fifth']

# ['second', 'third']

# 'fifth'

# ['second', 'third', 'fourth']

# ['first', 'second', 'third', 'fourth', 'fifth']

# ['first', 'second', 'third', 'fourth']

# ['third', 'fourth', 'fifth']

Slicing won't change the original list, instead it returns a new list containing all items of the list starting with the first index, and up to but not including the second index.

Add items to list:

l.insert(2, 'between 2 and 3')
# ['first', 'second', 'between 2 and 3', 'third', 'fourth', 'fifth']

# ['first', 'second', 'between 2 and 3', 'third', 'fourth', 'fifth', 'sixth']

l.extend(['seventh', 'eighth'])
# ['first', 'second', 'between 2 and 3', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth']

append takes a single item, and add it to the end of the list.
extend concatenates two lists.

Remove items from list:

l = ['first', 'second', 'third', 'fourth', 'fifth']
# ['second', 'third', 'fourth', 'fifth']
# ValueError: list.remove(x): x not in list

item = l.pop()
# item: 'fifth'
# l: ['first', 'second', 'third', 'fourth']

List operators:

l = ['first', 'second', 'third', 'fourth', 'fifth']
l += ['sixth', 'seventh']
# ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']

l = ['first', 'second']
l = l * 3
# ['first', 'second', 'first', 'second', 'first', 'second']

+ operator returns a new list, however, the extend function only modifies the existing list.

Search in list:

# 9

# 1

l.index('something else')
# ValueError: list.index(x): x not in list

'something else' in l
# False

The built-in range function returns a list of integers:

# [0, 1, 2, 3, 4]


Immutable list. Faster than list. Tuples and lists can be converted back and forth.

tuple(['a', 'b', 'c'])
# ('a', 'b', 'c')

list(('a', 'b', 'c'))
# ['a', 'b', 'c']

t = ('a', 'b', 'c', 'd')
# AttributeError: 'tuple' object has no attribute 'index'

'b' in t
# True

Assign multiple values:

(x, y, z) = ('a', 'b', 'c')
# x: 'a'
# y: 'b'
# z: 'c'

One-element tuple:

one = 1
t = (one,)

The comma after one is necessary. Without the comma, python won't know whether (one) is a tuple or a value of one.

Tuple can be used in string formatting (see below).

Formatting string

print "Hello, %s" % "world"
# Hello, world

print "Good %s, %s" % ("morning", "David")
# Good morning, David

print "The result is %d" % 7
# The result is 7

print "The result is " + 7
# TypeError: cannot concatenate 'str' and 'int' objects

print "Rate: %f" % 7.6864
# Rate: 7.686400

print "Rate: %.2f" % 7.6864
# Rate: 7.68

List comprehension

l1 = [1, 2, 3, 4]
l2 = [i * 2 for i in l1]
# l1: [1, 2, 3, 4]
# l2: [2, 4, 6, 8]

d = {'firstname': 'david', 'lastname': 'cai'}
["%s: %s" % (k, v) for k, v in d.items()]
# ["firstname: david", "lastname: cai"]

list = [1, 2, 3]
['%s' % item for item in list if item % 2 == 0]
# ['2']

List <---> string

str = ",".join(['a', 'b', 'c'])
# "a,b,c"

# ['a', 'b', 'c']

str.split(",", 1)
# ['a', 'b,c']

split takes a optional second argument which is the number of split.

Default and named arguments

def sayHello(firstname, lastname='cai'):

# David Cai

sayHello('David', 'Smith')
# David Smith

sayHello(lastname='Smith', firstname='David')
# David Smith

Arguments are actually a dictionary in Python. Calling function without argument names is simply a shorthand.


  1. great little summary, I might try to organize this into a printable sheet.