Hi, my name is Jesse and I abuse list comprehensions.

by jesse in ,

I just found myself being quite abusive. I have a series of dict{key:[list]) style objects, and I wanted to unpack it, convert it to a string, etc. (yes, variable names have been changed to protect the innocent)

return ',',join(['{{whizbang|%s}}' % i['foo'] for i in [ i for i in myDict[keyname]]])

Now, this could only be better if I:

  • Included a lambda
  • Had another nested comprehension

Other than the fact that what I wrote above is next to untestable - it's also hard to understand unless well, you're me. In order to debug it, you'd have to pprint the inbound dict and slowly unravel (from left to right) the operations being done.

Luckily, there's no math there!

So, I "cleaned" it up:

whizlist = []
for item in [k for k in myDict[keyname]]:
    whizlist.append('{{whizbang|%s}}' % item['foo'])
return ','.join(whizlist)

Hmm, I still seem to be juggling chainsaws here. Let's go for the "easy" button:

whizlist = []
for item in myDict[keyname]:
	whizlist.append('{{whizbang |%s}}' % item['foo'])
return ','.join(whizlist)

I could argue that the first is "faster" (although I'd need to prove it) - but ultimately the final "un-optimized" version is more pythonic.