newbie - concatanating 2 lists

Adam DePrince adam at deprince.net
Wed Feb 21 15:56:57 EST 2001


Remco Gerlich wrote:
> Sean 'Shaleh' Perry <shaleh at valinux.com> wrote in comp.lang.python:
> > On 21-Feb-2001 Gnanasekaran Thoppae wrote:
> > > i am just beginning to use python.
> > > i have:
> > > li1 = ['a', 'b', 'c']
> > > li2 = ['x', 'y', 'z']
> > > i want:
> > > li3 = ['ax', 'by', 'cz']
> > > how do i do it?
> > python 2 has a lovely function called zip(), maybe it could help.  Otherwise, a
> > quick map would probably do this.
> For Python 2, with zip and list comprehensions, it would look like
> li3 = [a+b for a,b in zip(li1,li2)]
> Hmm, or even
> li3 = map(''.join, zip(l1,l2))
> I like
> li3 = map(operator.add, li1, li2)
> best (why do people write their own lambda for operator.add? :)).
> But all of these are trying to get it to fit in the least number of
> characters (and they're pretty fast, although I have doubts about the zip
> things).
> A newbie should also understand the basic way:
> 
> A = ['a','b','c']
> B = ['d','e','f']
> C = []
> for i in range(len(A)):

And if you want to handle mismatched lists gracefully ... 

  for i in range(min((len(A),len(B)))):


>    C.append(A[i]+B[i])
> 
> This will give an exception if l1 is longer than l2, but all the above
> methods have problems with different length lists as well.
> 
> zip(), list comprehensions, string methods etc are cool, but we end up
> with a lot of ways to do it...
> --
> Remco Gerlich



More information about the Python-list mailing list