Ronnie Lale
Ronnie Lale

Reputation: 3

Assign values to an array using two values

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

Answers (3)

Moses Koledoye
Moses Koledoye

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

hibernado
hibernado

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

Feodoran
Feodoran

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

Related Questions