How to generate "a, b, c, and d"?

MRAB python at mrabarnett.plus.com
Thu Dec 15 14:27:09 EST 2011


On 15/12/2011 18:51, Tim Chase wrote:
> On 12/15/11 12:19, Ethan Furman wrote:
>> Tim Chase wrote:
>>> On 12/15/11 10:48, Roy Smith wrote:
>>>> I've got a list, ['a', 'b', 'c', 'd'].  I want to generate the
>>>> string, "a, b, c, and d" (I'll settle for no comma after 'c').
>>>> Is there some standard way to do this, handling all the special
>>>> cases?
>>>
>>> If you have a list, it's pretty easy as MRAB suggests.  For
>>> arbitrary iterators, it's a bit more complex.  Especially with
>>> the odd edge-case of 2 items where there's no comma before the
>>> conjunction (where>2 has the comma before the conjunction).  If
>>> you were willing to forgo the Oxford comma, it would tidy up the
>>> code a bit.
>>
>> Why go through all that instead of just converting the iterator
>> into a list at the beginning of MRAB's solution and then running
>> with it?
>
> For the fun/challenge?  Because you have a REALLY big data source
> that you don't want to keep in memory (in addition the resulting
> string)?
>
> Yeah, for most non-pathological cases, it would make more sense to
> just make it a list and then deal with the 4 cases (no elements, one
> element, 2 elements, and>2 elements) individually.
>
I was going to question it too, but then I wondered what would happen if
there were a very large number of items and the string would be too big
for memory, for example, writing a list of all the numbers from one to a
billion to a file.



More information about the Python-list mailing list