else in list comp

Cliff Wells clifford.wells at attbi.com
Tue Jan 28 23:35:04 EST 2003


On Tue, 2003-01-28 at 20:26, Andrew Bennetts wrote:
> On Tue, Jan 28, 2003 at 08:05:25PM -0800, Cliff Wells wrote:
> > 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', '']
> 
> This doesn't solve the general problem, but...
> 
>     >>> l = ['mary', 'had', 'a', 'little', None]
>     >>> [x or '' for x in l]
>     ['mary', 'had', 'a', 'little', '']

Yes, but that wasn't really my point =)  I was soliciting comments on an
else clause in list comps.

Also, consider how to replace None with '' in the following list:

[0, None, '1', None, 2, None, '3']

This is actually closer to my real situation (0 is a possibility). My
first example was poor.  Sorry.

-- 
Cliff Wells <clifford.wells at attbi.com>






More information about the Python-list mailing list