Skip to content

Data-centric Programming

by admin on July 25th, 2010

Busywork code is not important. Data is important. And data is not difficult. It’s only data. If you have too much, filter it. If it’s not what you want, map it. Focus on the data; leave the busywork behind

– Dive into Python

Here are some of my examples

def odd(i):
    return i % 2

a = range(10)
b = filter(odd, a)
a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b
[1, 3, 5, 7, 9]

x=[1,-2,3,4,-34]
y = filter(lambda z: z > 0, x)
y
[1,3,4]
# list comprehension
d = [i*2 for i in a]
d
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

map(len,["Oracle","MySQL"])
[6,5]

You could do the same thing with a for loop. Functions like filter are much more expressive. Not only is it easier to write, it’s easier to read, too. Reading the for loop is like walking in woods, you see all the details, but you won’t see the bigger picture until you are out of the woods.

c = []
for n in a:
    if odd(n):
        c.append(n)
c
[1, 3, 5, 7, 9]

From → Python

No comments yet

Leave a Reply

You must be logged in to post a comment.