How to concatenate list members

Terry Reedy tjreedy at udel.edu
Thu May 30 10:08:01 EDT 2002


"Eric Brunel" <eric.brunel at pragmadev.com> wrote

> Ruediger Maehl wrote:
> > I know, I can use a for loop over all elements and concatenate
> > them to one string. But is there another more efficient solution?
> >
> > def concat1(alist, sep=" "):
> >     res = ""
> >     for e in alist:
> >         res += str(e)
> >         res += sep
> >     return res[:-1]
> >
> > a = ["200100002", "200100003", "200100004"]  # many many more to
come ...
> >
> > b = concat1(a, "_")
> > # "200100002_200100003_200100004"

> Try this:
>
> def concat1(alist, sep=" "):
>   if not alist: return ''
>   return reduce(lambda x,y,sep=sep: x + sep + y, alist)
>
> The "if" is necessary because as it's written, the reduce won't work
on empty lists.
> If you like one-liners, you can also do this:
> b = (a and reduce(lambda x,y: x + "_" + y, a)) or ''

Add '' as the third parameter to reduce and it will work with empty
lists ...
but adds an extra separator for non-empty lists ... as  the OP
discovered ...

>>> a = ["200100002", "200100003", "200100004"]
>>> reduce(lambda x,y: x + "_" + y, a, '')
'_200100002_200100003_200100004'
>>> reduce(lambda x,y: x + "_" + y, [], '')
''

However, any reduce version is algorithmically equivalent to a for
loop:
it has the same quadratic behavior and does not answer the quest for
the linear
behavior that .join() provides.  .join() also properly handles the 0
versus n-1 separators problem

Terry J. Reedy






More information about the Python-list mailing list