Re: Feature Proposal: Sequence .join method
- From: "Terry Reedy" <tjreedy@xxxxxxxx>
- Date: Fri, 30 Sep 2005 12:23:56 -0400
"David Murmann" <david.murmann@xxxxxxxxxxxxxx> wrote in message
news:3q3pt9Fd7pklU1@xxxxxxxxxxxxxxxxx
>> def join(sep, seq):
>> return reduce(lambda x, y: x + sep + y, seq, type(sep)())
>
> damn, i wanted too much. Proper implementation:
>
> def join(sep, seq):
> if len(seq):
> return reduce(lambda x, y: x + sep + y, seq)
> return type(sep)()
>
> but still short enough
For general use, this is both too general and not general enough.
If len(seq) exists then seq is probably reiterable, in which case it may be
possible to determine the output length and preallocate to make the process
O(n) instead of O(n**2). I believe str.join does this. A user written
join for lists could also. A tuple function could make a list first and
then tuple(it) at the end.
If seq is a general (non-empty) iterable, len(seq) may raise an exception
even though the reduce would work fine.
Terry J. Reedy
.
- References:
- Re: Feature Proposal: Sequence .join method
- From: David Murmann
- Re: Feature Proposal: Sequence .join method
- Prev by Date: Re: getattr
- Next by Date: Re: Will python never intend to support private, protected and public?
- Previous by thread: Re: Feature Proposal: Sequence .join method
- Next by thread: Re: Feature Proposal: Sequence .join method
- Index(es):