Python list filtering

One of the really nice features of Python is list filtering. This feature basically let's you do some quite powerful one liners.

Here is an example I did today:

friends = Users().getFriends(user_id) #All friends
if friends_to_fetch:
    friends = [ id for id in friends_to_fetch if id in friends ]

If friends_to_fetch is set, then we filter friends and add id's that both are in friends and friends_to_fetch.

Read more about list filtering in Dive Into Python [which is an excellent Python book].

Code · Code improvement · Python · Tips 23. Dec 2007
© Amir Salihefendic. Powered by Skeletonz.