Wednesday, January 6, 2010

list comprehensions in python

One of my favorite features of python is a functional language feature that python itself borrowed - list comprehensions.

I just think it is wonderfully elegant if a language can do something like this:

Example 1:

lines = ['now is the time\r\n']
lines.append(' for all good men ')
lines.append(' to come to the aid of their country\n')

# Does not modify list, returns a new list
lines = [line.strip() for line in lines]

print lines

>>>['now is the time', 'for all good men', 'to come to the aid of their country']

Example 2:

lines = ['<act> is the next act']
lines.append('performing at our show')
lines.append('please give <act> a big round of applause')

print [line.replace('<act>', 'Go Dog Go') for line in lines]
print [line.replace('<act>', 'The Beatles') for line in lines]

>>>['Go Dog Go is the next act', 'performing at our show', 'please give Go Dog Go a big round of applause']

>>>['The Beatles is the next act', 'performing at our show', 'please give The Beatles a big round of applause']

You can do simple operations like strip and replace or even an in place lambda on every element of a list and return that list... all in one line.

I love Python and its functional cousin languages.

No comments: