Reputation: 3
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.
Upvotes: 0
Views: 36
Reputation: 78556
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!
Upvotes: 2
Reputation: 1770
'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)]
Upvotes: 0
Reputation: 1822
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.
Upvotes: 0