else in list comp
Cliff Wells
clifford.wells at attbi.com
Tue Jan 28 23:05:25 EST 2003
Maybe this has come up before, but I haven't heard a discussion of list
comps in a while so here's something I thought might be interesting:
I was looking for a fast, clean way of converting a single value in a
list to a different value (specifically None to ''). It occurred to me
to use a list comp and this seemed the most straightforward solution:
Given the list:
l = ['mary', 'had', 'a', 'little', None]
it should get mapped to ['mary', 'had', 'a', 'little', '']
What I thought of first:
['' for i in l if i is None else i]
Now clearly this isn't valid Python code, but it seemed natural. The
working solution I actually used is:
[[i, ''][i is None] for i in l]
which doesn't seem nearly as nice, and likely less efficient (due to the
additional list lookup) than the non-existent alternative.
Any thoughts on something like this? Has this come up before (I'm not
sure exactly how I'd Google for this) and been rejected?
--
Cliff Wells <clifford.wells at attbi.com>
More information about the Python-list
mailing list