By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,942 Members | 1,788 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,942 IT Pros & Developers. It's quick & easy.

multiplying indeces

P: 31
say i have L=[1,2,3] and L2=[2,3,4], how i i write a function that multiplies the same indeces together and return as a list?....the answer to the example would be [2,6,12]..

-mike
Feb 22 '09 #1
Share this Question
Share on Google+
4 Replies


FlamingoRider
P: 11
Just made an empty list and wrote a function to mulitply and put the answer into the list.

Expand|Select|Wrap|Line Numbers
  1. L = [1,2,3]
  2. L2 = [2,3,4]
  3. multList = []
  4.  
  5. def multInde():
  6.     multList.append(L[0]*L2[0])
  7.     multList.append(L[1]*L2[1])
  8.     multList.append(L[2]*L2[2])
  9.  
  10. multInde()
  11. print multList
  12.  
Feb 22 '09 #2

Smygis
100+
P: 126
A list comprehension with some zip in it,
Expand|Select|Wrap|Line Numbers
  1. >>> l1 =[1,2,3]
  2. >>> l2 = [2,3,4]
  3. >>> [l[0]*l[1] for l in zip(l1,l2)]
  4. [2, 6, 12]
  5. >>> 
  6.  
Feb 22 '09 #3

boxfish
Expert 100+
P: 469
Interesting; I didn't know about zip. Another solution:
Expand|Select|Wrap|Line Numbers
  1. [L[i] * L2[i] for i in xrange(len(L))]
Feb 22 '09 #4

bvdet
Expert Mod 2.5K+
P: 2,851
My contribution, using zip().

Expand|Select|Wrap|Line Numbers
  1. >>> L1=[1,2,3]
  2. >>> L2=[2,3,4]
  3. >>> [a+b for a, b in zip(L1, L2)]
  4. [3, 5, 7]
  5. >>> 
Feb 23 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.