multiplying indeces

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v13tn1g
    New Member
    • Feb 2009
    • 31

    multiplying indeces

    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
  • FlamingoRider
    New Member
    • Feb 2009
    • 11

    #2
    Just made an empty list and wrote a function to mulitply and put the answer into the list.

    Code:
    L = [1,2,3]
    L2 = [2,3,4]
    multList = []
    
    def multInde():
        multList.append(L[0]*L2[0])
        multList.append(L[1]*L2[1])
        multList.append(L[2]*L2[2])
    
    multInde()
    print multList

    Comment

    • Smygis
      New Member
      • Jun 2007
      • 126

      #3
      A list comprehension with some zip in it,
      Code:
      >>> l1 =[1,2,3]
      >>> l2 = [2,3,4]
      >>> [l[0]*l[1] for l in zip(l1,l2)]
      [2, 6, 12]
      >>>

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Interesting; I didn't know about zip. Another solution:
        Code:
        [L[i] * L2[i] for i in xrange(len(L))]

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          My contribution, using zip().

          Code:
          >>> L1=[1,2,3]
          >>> L2=[2,3,4]
          >>> [a+b for a, b in zip(L1, L2)]
          [3, 5, 7]
          >>>

          Comment

          Working...