How to concatenate list members

Eric Brunel eric.brunel at pragmadev.com
Thu May 30 10:18:15 EDT 2002


Ruediger Maehl wrote:
> I would like to concatenate all members of a list of strings.
> How can I do that?
> 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, "_")
> 
> print b
> 
> # and b then looks like this:
> # "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 ''

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list