Add two lists in Python

12,930

Solution 1

What you should do

You should use

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

instead of

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

In your version, you never say that you want the plus character in the output between the two elements. This is your error.

Sample output:

>>> a = [1,2,3]
>>> b = ['a','b','c']
>>> list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
>>> list
['1+a', '2+b', '3+c']

Solution 2

Zip first, then add (only not).

['%s+%s' % x for x in zip(a, b)]
Share:
12,930
George Burrows
Author by

George Burrows

Updated on June 04, 2022

Comments

  • George Burrows
    George Burrows almost 2 years

    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.