I’m trying to multiply two arrays without using numpy. But, I receive an error on the line “multi = a[i]*b[j]” stating that the index is out of range.
a = [1,2,3]
b = [4,5,6]
multi = [0,0,0,0,0,0,0,0]
for i in a:
for j in b:
multi = a[i]*b[j]
append.multi(y)
print multi
Lets start with what you were trying. The for loop:
Now, I would suggest you have a read here python data structures
Once you understand how to use a for loop, understanding list comprehensions is easy.
The are the same for loop, but but the results go straight into a list. this is nice. In-fact it is so nice that nearly everybody does it this way.
so, instead of
for ... ab.append(x * y)we write[ x * y for ... ]now if the code was written like this:
it would make it a generator. Lots of people use these as well. Think of these as lazy lists. You can put things in it, but it is not evaluated until you try and do something with it.
if you ‘were’ trying to solve this using the indexes, I would probably use:
you can also do fun things like:
if you used:
you would create a map object… which is very much the same as the
< generator >.or if you had three lists:
and if you really wanted to you could do: