newbie - concatanating 2 lists
scarblac at pino.selwerd.nl
Thu Feb 22 11:01:26 CET 2001
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))
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
A newbie should also understand the basic way:
A = ['a','b','c']
B = ['d','e','f']
C = 
for i in range(len(A)):
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...
More information about the Python-list