Thursday, October 02, 2008

List Comprehension in Python, an example

Coding up a little website where a user would select (using check boxes) from a list of items and submit. I'm using Django btw (which is great). Due to the dynamic nature of the list being generated and displayed, the name of each checkbox wold be something like vid0, vid1, etc. The POST data however will not have the keys for unsubmitted values, and I have no way to tell which keys are in the POST dictionary.

So at first, I coded the following bit of code. Simple, straightforward, gets the job done.
feed = []
for i in range(max_results):
feed.append(request.POST.get('vid'+str(i), '')) # feed will contain empty strings
if feed[-1] is '':
del feed[-1] #if the most recently appended item is an empty string, delete it.
But then, I had a light bulb moment and coded this:
feed=[request.POST.get('vid'+str(i)) for i in range(max_results) if request.POST.get('vid'+str(i),'') is not '']
One line of code now replaces 5! How awesome is that! Python rocks.

There might be even simpler and more elegant solutions out there. If so, please leave them in the comments. (Maybe something using a lambda?)

BTW, I am a newcomer to python having started to code with it just a few months ago.

Labels: , , , , , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home