Idea for joined() builtin

Rhamphoryncus rhamph at gmail.com
Thu Aug 16 21:21:24 CEST 2007


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




More information about the Python-list mailing list