By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,742 Members | 1,224 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,742 IT Pros & Developers. It's quick & easy.

Idea for joined() builtin

P: n/a
I know similar things have been argued before, but little things (like
the joined name implying a copy) can make a big difference. That and
I'm providing a simple implementation that works right now, so you
don't have to wait for it to ever become a builtin. ;)
>>joined([], [[1,2,3], [4,5,6]])
[1, 2, 3, 4, 5, 6]
>>joined(' ', ['hello', 'world'])
'hello world'

def joined(sep, iterable):
if hasattr(sep, 'join'):
return sep.join(iterable) # string-like interface
else:
output = type(sep)() # Hopefully an empty container
for i in iterable:
output.extend(i) # list-like interface
output.extend(sep)
else:
if sep:
del output[-len(sep):]
return output

A little commentary on the intended usage. There are three common
ways to "combine" objects:

The first is adding numbers together. This may be accomplished with a
+b or sum([a, b]). All values affect the output, but their
individuality is lost; you cannot extract the original values[1].

The second is concatenation. This is usually done with list.extend,
''.join(), or with my joined function. It can also be done with a+b,
but the performance is substantially worse if done repeatedly. All
values affect the output and most of their individuality is retained;
given the original lengths of the subsequences, you can extract them
from the combined form.

The third is the "or" operation of a set or integer. This is done
with a|b. The values usually have some effect on the output, but as
redundant entries are removed, they lose a significant part of their
individuality.

The important thing to realize is that all of these different ways of
"combining" objects has different conceptual behaviour and different
performance characteristics. Get them confused or attempt to over-
generalize and you will be bitten.
[1] Math/crypto has some exceptions. Stop mentally poking holes in my
argument. :)

--
Adam Olsen, aka Rhamphoryncus

Aug 16 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.