Got to love syntactic sugar

Syntactic in languages is pretty important and I think that Python has the right amounts of it. I especially like Python's syntactic sugar for lists.

In Python there are different ways to filter a list, here is an example:

unread_plurks = [(1, 0), (2, 1), (3, 5), (4, 7), (5, 5)]
muted_list = [1, 3]

#The ugly
new_list = []
for id, count in unread_plurks:
    if id not in muted_list:
        new_list.append((id, count))

#The Pythonic way
new_list = [ (id, c) for id, c in unread_plurks\
             if id not in muted_list ]

#The functional way
new_list = filter(lambda item: item[0] not in muted_list,
                  unread_plurks)

I prefer the Pythonic way, it's pretty readable and it's super easy to create a generator out of it, e.g.:

new_list = ( (id, c) for id, c in unread_plurks\
             if id not in muted_list )
Code · Python · Tips 15. Dec 2008
© Amir Salihefendic. Powered by Skeletonz.