5

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.

2 Answers 2

9

Zip first, then add (only not).

['%s+%s' % x for x in zip(a, b)]
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I should have mentioned, I have to write a function that will essentially perform the same as zip(a,b) but I'm not allowed to use zip() anywehere in the function.
So then adapt what you already have and use that in place of zip().
3

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']

4 Comments

I still get the same 'cannot cocatenate 'str' and 'int' objects.'
@GeorgeBurrows How did you get that ['a1','b2','c3','d4'] without error so, could your detail?
By using: list = [str(a[i]) + str(b[i]) for i in range(len(a))]
@GeorgeBurrows What about the snipped I just typed in my python log with exactly the same line I gave you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.