Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two lists in Python

I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list.

Currently I have:

def zipper(a,b):
    list = [a[i] + b[i] for i in range(len(a))]
    print 'The combined list of a and b is'
    print list

a = input("\n\nInsert a list:")
b = input("\n\nInsert another list of equal length:")

zipper(a,b)

Upon entering two lists where one is a list of integers and one a list of strings I get the Type Error 'Can not cocanenate 'str' and 'int' objects.

I have tried converting both lists to strings using:

list = [str(a[i]) + str(b[i]) for i in range(len(a))]

however upon entering:

a = ['a','b','c','d']
b = [1,2,3,4]

I got the output as:

['a1','b2','c3','d4']

instead of what I wanted which was:

['a+1','b+2','c+3','d+4']

Does anyone have any suggestions as to what I am doing wrong?

N.B. I have to write a function that will essentially perform the same as zip(a,b) but I'm not allowed to use zip() anywhere in the function.

like image 693
George Burrows Avatar asked Oct 31 '11 00:10

George Burrows


1 Answers

Zip first, then add (only not).

['%s+%s' % x for x in zip(a, b)]
like image 66
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 22:09

Ignacio Vazquez-Abrams