Transforming a list of data in Python

From XPUB & Lens-Based wiki
Revision as of 14:43, 5 April 2011 by Inge Hoonte (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Exercise to be typed in ipython.

To test, you can use the range function to get some "sample" data to work with:

data = range(100)

for d in data:
    print d

Imagine you want to multiply each number by 17.

for d in data:
    print d*17

Iterate & Append to a new list

A general purpose technique to translate the items of one list to another is to:
1. Create a new empty list
2. Iterate over the original list
3. Use the list.append function to add (transformed) items onto the new list

pp = []
for d in data:
    pp.append(d)
pp

pp = []
for d in data:
    pp.append(d*17)
pp

List comprehensions

Python also supports a more mathematically inspired notation called List Comprehensions. The result is more compact, and may or may not be easier to read.

p = range(100)
pp = [x*17 for x in p]