else in list comp

Bengt Richter bokr at oz.net
Wed Jan 29 05:21:22 EST 2003


On 28 Jan 2003 22:17:04 -0800, Cliff Wells <clifford.wells at attbi.com> wrote:

>On Tue, 2003-01-28 at 21:36, David Eppstein wrote:
>> In article <mailman.1043813212.6357.python-list at python.org>,
>>  Cliff Wells <clifford.wells at attbi.com> wrote:
>> 
>> > Given the list:
>> > 
>> > l = ['mary', 'had', 'a', 'little', None]
>> > 
>> > it should get mapped to ['mary', 'had', 'a', 'little', '']
>> 
>> [x or '' for x in l]
>
>Yes, this was suggested by someone else, but again, solving the
>particular problem wasn't the real point.  If the data contains anything
>that evaluates to false (such as 0), then x or '' won't work.  I stated
>the problem badly which led to this confusion.  My apologies.
>
>Kindly reconsider the problem using 
>
>myList = [0, None, '1', None, 2, None, '3']
>
 >>> myList = [0, None, '1', None, 2, None, '3']
 >>> [(x, '')[x is None] for x in myList]
 [0, '', '1', '', 2, '', '3']

>My real interest was in a possible "else" clause (as per the subject
>line) in a list comp.
>
>['' for i in myList if i is None else i]
The alternatives are separated pretty far, though, so the choices
and conditions don't read as clearly as the solution above, IMO, though that
is not beautiful either.

>
>It seems a good idea to me, but then, I'm somewhat biased toward my own
>ideas.
I know the feeling ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list