Beginner question: Converting Single-Element tuples to list

John Roth newsgroups at jhrothjr.com
Mon Jun 27 16:21:41 CEST 2005


"Reinhold Birkenfeld" <reinhold-birkenfeld-nospam at wolke7.net> wrote in 
message news:3i9jdvFkhd21U1 at individual.net...
> vdavidster at gmail.com wrote:
>> Hi,
>>
>> Thanks for your reply! A new thing learned....
>>
>> Allow me to follow that up with another question:
>>
>> Let's say I have a result from a module called pyparsing:
>>
>> Results1 = ['abc', 'def']
>> Results2 = ['abc']
>>
>> They are of the ParseResults type:
>>
>>>>> type(Results1)
>> <class 'pyparsing.ParseResults'>
>>>>> type(Results2)
>> <class 'pyparsing.ParseResults'>
>>
>> I want to convert them into Python lists. list() will work fine on
>> Results1, but on Results2, it will return:
>>
>> ['a', 'b', 'c']
>>
>> Because 'abc' is a string. But I want it to return ['abc'].
>>
>> In short, my question is: how do I typecast an arbitrary object,
>> whether a list-like object or a string, into a Python list without
>> having Python split my strings into characters?
>
> This seems like a glitch in pyparsing. If a ParseResults class emulates
> a list, it should do so every time, not only if there is more than one
> value in it.

Unfortunately, I've seen that behavior a number of times:
no output is None, one output is the object, more than one
is a list of objects. That forces you to have checks for None
and list types all over the place. Granted, sometimes your
program logic would need checks anyway, but frequently
just returning a possibly empty list would save the caller
a lot of grief.

John Roth
>
> Reinhold 




More information about the Python-list mailing list