David Abel

Portrait


Python Tutorial

python logo

This tutorial is intended as an introduction to Python for folks with some prior programming experience.

Section 7: Tips and Tricks: (no file)

A favorite trick of many python programmers is the list comprehension, which allows easy creation of lists in a single line (sometimes at the loss of readability). The syntax is:

>>> my_list = [<var> for <var> in <list>]

For instance:

>>> my_list = [x for x in range(10)]

You're probably wondering why you would do this if you can simply call: list_of_ints = range(10). The neatest part about list comprehensions is adding conditionals, and nesting comprehensions. For instance:

>>> my_list = [x for x in range(10) if x % 4 == 0]
>>> print my_list
[0,4,8]

Pretty cool! You can nest list comprehensions, too:

>>> my_list = [[x for x in range(10) if x % 4 == 0] for j in range(3)]
>>> print my_list
[[0,4,8],[0,4,8],[0,4,8]]

Alternatively, you may multiplty a list by an integer N to create a new list with the old list repeated N times:

>>> my_list = [0,4,8]*2
>>> print my_list
[0,4,8,0,4,8]

Another nice trick is the built in enumerate() function. This allows you to easily enumerate long lists of data. For instance:

>>> states = ["Washington", "Oregon", "California"]
>>> my_list = list(enumerate(states))
>>> print my_list
[(0, "Washington"), (1, "Oregon"), (2, "California")]

You can also specify a starting integer:

>>> states = ["Washington", "Oregon", "California"]
>>> my_list = list(enumerate(states), start=3)
>>> print my_list
[(3, "Washington"), (4, "Oregon"), (5, "California")]

Another function you will likely find helpful is zip(). This takes two lists of equal length and returns a list of tuples consisting of the i-th element from each list paired together. For instance:

>>> a = [0,1]
>>> b = [2,3]
>>> zipped = zip(a, b)
>>> print zipped [(0,2), (1,3)]

Python also allows for multiple assignments on one line:

>>> x = 5
>>> y = 7
>>> x, y = y,x
>>> print x
7
>>> print y
5

This is also the best way to return multiple values from a function.

def get_key_value_pair(data):
    # function body
    return key, val
K,V = get_key_value_pair(data)

And that's all I've got for now! Happy Pythoning! If you have any suggestions to improve this tutorial, email me at dmabel@google.com

< Previous Section