0

I am trying to generate an array that is the sum of two previous arrays. e.g

c = [A + B for A in a and B in b]

Here, get the error message

NameError: name 'B' is not defined

where

len(a) = len(b) = len(c)

Please can you let me know what I am doing wrong. Thanks.

2
  • Can you clarify whether you want to sum each element with the same index together (i.e. len(a) = len(b) = len(c)), or do a cartesian sum (len(c) = len(a)*len(b))? Commented Apr 27, 2017 at 15:45
  • len(a) = len(b) = len(c) Commented Apr 27, 2017 at 15:48

3 Answers 3

2

The boolean and operator does not wire iterables together, it evaluates the truthiness (or falsiness) of its two operands.

What you're looking for is zip:

c = [A + B for A, B in zip(a, b)]

Items from the two iterables are successively assigned to A to B until one of the two is exhausted. B is now defined!

Sign up to request clarification or add additional context in comments.

Comments

0

It should be

c = [A + B for A in a for B in b]

for instead of and. You might want to consider using numpy, where you can add 2 matrices directly, and more efficient.

3 Comments

I tried running the code you suggested and it seemed to iterate through each value in b, for each value of a, creating a list of 9 elements, not 3, which was what I was trying to do in the OP. I will try using numpy in future if I have larger list. Thanks :)
Can you clarify your question? It's not clear from the current wording whether you want Feodoran's solution or Moses'
Right, that is why the other guys suggested to use zip(). Anyway with numpy you get much cleaner code.
0

'for' does not work the way you want it to work. You could use zip().

A = [1,2,3]
B = [4,5,6]
c = [ a + b for a,b in zip(A,B)]

zip iterates through A & B and produces tuples. To see what this looks like try:

[ x for x in zip(A,B)]

Comments

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.