functions on arrays of different sizes in for loopWhat is the difference between @staticmethod and @classmethod?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Accessing the index in 'for' loops?Loop through an array in JavaScriptIterating over dictionaries using 'for' loopsHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Transfer over $10k

Reverse the word in a string with the same order in javascript

Confusion about capacitors

What does "rf" mean in "rfkill"?

Why didn't this hurt this character as badly?

Why the difference in metal between 銀行 and お金?

Why do TACANs not have a symbol for compulsory reporting?

Where did the extra Pym particles come from in Endgame?

How to figure out whether the data is sample data or population data apart from the client's information?

How to verbalise code in Mathematica?

How does a Swashbuckler rogue "fight with two weapons while safely darting away"?

Lock in SQL Server and Oracle

Why do computer-science majors learn calculus?

Multiple options for Pseudonyms

Are Boeing 737-800’s grounded?

If Earth is tilted, why is Polaris always above the same spot?

TikZ how to make supply and demand arrows for nodes?

Has any spacecraft ever had the ability to directly communicate with civilian air traffic control?

Can I get candy for a Pokemon I haven't caught yet?

Feels like I am getting dragged in office politics

Please, smoke with good manners

Does jamais mean always or never in this context?

Illegal assignment from SObject to Contact

Binary Numbers Magic Trick



functions on arrays of different sizes in for loop


What is the difference between @staticmethod and @classmethod?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Accessing the index in 'for' loops?Loop through an array in JavaScriptIterating over dictionaries using 'for' loopsHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I have two arrays of different sizes that I want to perform logical functions on in a for loop. For example, if I have:



array1 = [6,7,8]
array2 = [1,2,3,4,5]


I want to do each element from array1 minus each element of array2 to get something like



[6-1,6-2,6-3,6-4,6-5],[7-1,7-2,7-3,7-4,7-5],[8-1,8-2,8-3,8-4,8-5]



which is subtracting each element from array2 from each element of array1



So i tried to do a for loop like:



for i in range(len(array1)):
ar = array1[i]-array2


and also



for i in range(len(array1)):
for j in range(len(array2)):
ar = array1[i]-array2[j]


But neither of these seem to be working



The first way seems to be returning an array of the right shape but certainly not the right values.



I'd like it to be returned in separate arrays because in reality, I have a very large sample size.










share|improve this question






























    2















    I have two arrays of different sizes that I want to perform logical functions on in a for loop. For example, if I have:



    array1 = [6,7,8]
    array2 = [1,2,3,4,5]


    I want to do each element from array1 minus each element of array2 to get something like



    [6-1,6-2,6-3,6-4,6-5],[7-1,7-2,7-3,7-4,7-5],[8-1,8-2,8-3,8-4,8-5]



    which is subtracting each element from array2 from each element of array1



    So i tried to do a for loop like:



    for i in range(len(array1)):
    ar = array1[i]-array2


    and also



    for i in range(len(array1)):
    for j in range(len(array2)):
    ar = array1[i]-array2[j]


    But neither of these seem to be working



    The first way seems to be returning an array of the right shape but certainly not the right values.



    I'd like it to be returned in separate arrays because in reality, I have a very large sample size.










    share|improve this question


























      2












      2








      2








      I have two arrays of different sizes that I want to perform logical functions on in a for loop. For example, if I have:



      array1 = [6,7,8]
      array2 = [1,2,3,4,5]


      I want to do each element from array1 minus each element of array2 to get something like



      [6-1,6-2,6-3,6-4,6-5],[7-1,7-2,7-3,7-4,7-5],[8-1,8-2,8-3,8-4,8-5]



      which is subtracting each element from array2 from each element of array1



      So i tried to do a for loop like:



      for i in range(len(array1)):
      ar = array1[i]-array2


      and also



      for i in range(len(array1)):
      for j in range(len(array2)):
      ar = array1[i]-array2[j]


      But neither of these seem to be working



      The first way seems to be returning an array of the right shape but certainly not the right values.



      I'd like it to be returned in separate arrays because in reality, I have a very large sample size.










      share|improve this question
















      I have two arrays of different sizes that I want to perform logical functions on in a for loop. For example, if I have:



      array1 = [6,7,8]
      array2 = [1,2,3,4,5]


      I want to do each element from array1 minus each element of array2 to get something like



      [6-1,6-2,6-3,6-4,6-5],[7-1,7-2,7-3,7-4,7-5],[8-1,8-2,8-3,8-4,8-5]



      which is subtracting each element from array2 from each element of array1



      So i tried to do a for loop like:



      for i in range(len(array1)):
      ar = array1[i]-array2


      and also



      for i in range(len(array1)):
      for j in range(len(array2)):
      ar = array1[i]-array2[j]


      But neither of these seem to be working



      The first way seems to be returning an array of the right shape but certainly not the right values.



      I'd like it to be returned in separate arrays because in reality, I have a very large sample size.







      python arrays






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 19:25









      Sayse

      29.9k115298




      29.9k115298










      asked Mar 22 at 19:09









      wiladawilada

      343




      343






















          7 Answers
          7






          active

          oldest

          votes


















          4














          We can solve this using itertools.product



          from itertools import product
          from operator import sub

          final = []
          for item in array1:
          prods = product([item], array2)
          subs = [sub(*p) for p in prods]
          final.append(subs)

          print(final)
          # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]


          How it works is product returns the cartesian product of the two arrays in the form of tuples, so:



          (6, 1), (6, 2), etc....


          Then we simply apply the sub function to each tuple using a list-comprehension.






          share|improve this answer

























          • Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

            – wilada
            Mar 22 at 19:14











          • The output you show here doesn't match the OP's expected output

            – Sayse
            Mar 22 at 19:15











          • product does not multiply but returns cartesian products

            – aws_apprentice
            Mar 22 at 19:15











          • Is there a way to do this with other more complicated functions? I just used subtraction as an example

            – wilada
            Mar 22 at 19:20











          • sure there is but without specifics I really can't answer or clarify

            – aws_apprentice
            Mar 22 at 19:20


















          3














          The following solution should work using a list comprehension:



          result = []
          for value1 in array1:
          result.append([value1 - value2 for value2 in array2])


          You could even write this in 1 line using both for loops for the list comprehension:



          result = [[value1 - value2 for value2 in array2] for value1 in array1]





          share|improve this answer






























            2














            Loops solution:



            array1 = [6, 7, 8]
            array2 = [1, 2, 3, 4, 5]

            arr = []
            for i in array1:
            tmp = []
            for j in array2:
            tmp.append(i - j)
            arr.append(tmp)

            print(arr)


            Output:




            [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]







            share|improve this answer






























              2














              Your for loop is nearly correct except, you overwrite the value of ar every iteration (and you make it slightly more complicated with range)



              You can achieve this through list comprehension



              [[i - j for j in array2] for i in array1]
              # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]





              share|improve this answer






























                1














                You were on the right track but you had your arrays switched. You want array1 inside the inner loop to perform the operation you want to perform:



                array1 = [6,7,8]
                array2 = [1,2,3,4,5]
                finalarray=[]

                for i in range(len(array2)):
                for j in range(len(array1)):
                ar = array1[j]-array2[i]
                finalarray.append(ar)

                print(finalarray)

                >>>[5, 6, 7, 4, 5, 6, 3, 4, 5, 2, 3, 4, 1, 2, 3]





                share|improve this answer






























                  1














                  ar is not being treated properly in your code, it needs to be an array of arrays (matrix) and you'll need another variable to hold the result per iteration, there's probably a better way to do this using list comprehensions but here is one way:



                  array1 = [6,7,8]
                  array2 = [1,2,3,4,5]

                  ar = []
                  row = []
                  for i in range(len(array1)):
                  for j in range(len(array2)):
                  row.append(array1[i]-array2[j])
                  ar.append(row)
                  row = []
                  print ar





                  share|improve this answer






























                    1














                    There are plenty of good answers here, but another option especially useful for larger arrays is to use numpy, a package designed for moving large arrays of numbers efficiently. One possible answer in numpy would be this:



                    import numpy as np

                    array1 = np.arange(6,9) # make arrays 1 and 2
                    array2 = np.arange(1,6)
                    output = (array1.repeat(array2.shape[0]) # repeat array1 as many times as there are elements in array2
                    .reshape(array1.shape[0], -1) # reshape so we have a row for each element in array1
                    ) - array2 # subtract array2 from each row
                    output


                    array([[5, 4, 3, 2, 1],
                    [6, 5, 4, 3, 2],
                    [7, 6, 5, 4, 3]])





                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function ()
                      StackExchange.using("externalEditor", function ()
                      StackExchange.using("snippets", function ()
                      StackExchange.snippets.init();
                      );
                      );
                      , "code-snippets");

                      StackExchange.ready(function()
                      var channelOptions =
                      tags: "".split(" "),
                      id: "1"
                      ;
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function()
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled)
                      StackExchange.using("snippets", function()
                      createEditor();
                      );

                      else
                      createEditor();

                      );

                      function createEditor()
                      StackExchange.prepareEditor(
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader:
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      ,
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      );



                      );













                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306357%2ffunctions-on-arrays-of-different-sizes-in-for-loop%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown

























                      7 Answers
                      7






                      active

                      oldest

                      votes








                      7 Answers
                      7






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      4














                      We can solve this using itertools.product



                      from itertools import product
                      from operator import sub

                      final = []
                      for item in array1:
                      prods = product([item], array2)
                      subs = [sub(*p) for p in prods]
                      final.append(subs)

                      print(final)
                      # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]


                      How it works is product returns the cartesian product of the two arrays in the form of tuples, so:



                      (6, 1), (6, 2), etc....


                      Then we simply apply the sub function to each tuple using a list-comprehension.






                      share|improve this answer

























                      • Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                        – wilada
                        Mar 22 at 19:14











                      • The output you show here doesn't match the OP's expected output

                        – Sayse
                        Mar 22 at 19:15











                      • product does not multiply but returns cartesian products

                        – aws_apprentice
                        Mar 22 at 19:15











                      • Is there a way to do this with other more complicated functions? I just used subtraction as an example

                        – wilada
                        Mar 22 at 19:20











                      • sure there is but without specifics I really can't answer or clarify

                        – aws_apprentice
                        Mar 22 at 19:20















                      4














                      We can solve this using itertools.product



                      from itertools import product
                      from operator import sub

                      final = []
                      for item in array1:
                      prods = product([item], array2)
                      subs = [sub(*p) for p in prods]
                      final.append(subs)

                      print(final)
                      # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]


                      How it works is product returns the cartesian product of the two arrays in the form of tuples, so:



                      (6, 1), (6, 2), etc....


                      Then we simply apply the sub function to each tuple using a list-comprehension.






                      share|improve this answer

























                      • Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                        – wilada
                        Mar 22 at 19:14











                      • The output you show here doesn't match the OP's expected output

                        – Sayse
                        Mar 22 at 19:15











                      • product does not multiply but returns cartesian products

                        – aws_apprentice
                        Mar 22 at 19:15











                      • Is there a way to do this with other more complicated functions? I just used subtraction as an example

                        – wilada
                        Mar 22 at 19:20











                      • sure there is but without specifics I really can't answer or clarify

                        – aws_apprentice
                        Mar 22 at 19:20













                      4












                      4








                      4







                      We can solve this using itertools.product



                      from itertools import product
                      from operator import sub

                      final = []
                      for item in array1:
                      prods = product([item], array2)
                      subs = [sub(*p) for p in prods]
                      final.append(subs)

                      print(final)
                      # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]


                      How it works is product returns the cartesian product of the two arrays in the form of tuples, so:



                      (6, 1), (6, 2), etc....


                      Then we simply apply the sub function to each tuple using a list-comprehension.






                      share|improve this answer















                      We can solve this using itertools.product



                      from itertools import product
                      from operator import sub

                      final = []
                      for item in array1:
                      prods = product([item], array2)
                      subs = [sub(*p) for p in prods]
                      final.append(subs)

                      print(final)
                      # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]


                      How it works is product returns the cartesian product of the two arrays in the form of tuples, so:



                      (6, 1), (6, 2), etc....


                      Then we simply apply the sub function to each tuple using a list-comprehension.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Mar 22 at 19:20

























                      answered Mar 22 at 19:12









                      aws_apprenticeaws_apprentice

                      3,9502723




                      3,9502723












                      • Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                        – wilada
                        Mar 22 at 19:14











                      • The output you show here doesn't match the OP's expected output

                        – Sayse
                        Mar 22 at 19:15











                      • product does not multiply but returns cartesian products

                        – aws_apprentice
                        Mar 22 at 19:15











                      • Is there a way to do this with other more complicated functions? I just used subtraction as an example

                        – wilada
                        Mar 22 at 19:20











                      • sure there is but without specifics I really can't answer or clarify

                        – aws_apprentice
                        Mar 22 at 19:20

















                      • Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                        – wilada
                        Mar 22 at 19:14











                      • The output you show here doesn't match the OP's expected output

                        – Sayse
                        Mar 22 at 19:15











                      • product does not multiply but returns cartesian products

                        – aws_apprentice
                        Mar 22 at 19:15











                      • Is there a way to do this with other more complicated functions? I just used subtraction as an example

                        – wilada
                        Mar 22 at 19:20











                      • sure there is but without specifics I really can't answer or clarify

                        – aws_apprentice
                        Mar 22 at 19:20
















                      Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                      – wilada
                      Mar 22 at 19:14





                      Product multiplies i guess right? I need it separated though by each action. Like I need different arrays for array1[1] - array2, array1[2] - array2, array1[3] - array2 because my real sample is much much bigger

                      – wilada
                      Mar 22 at 19:14













                      The output you show here doesn't match the OP's expected output

                      – Sayse
                      Mar 22 at 19:15





                      The output you show here doesn't match the OP's expected output

                      – Sayse
                      Mar 22 at 19:15













                      product does not multiply but returns cartesian products

                      – aws_apprentice
                      Mar 22 at 19:15





                      product does not multiply but returns cartesian products

                      – aws_apprentice
                      Mar 22 at 19:15













                      Is there a way to do this with other more complicated functions? I just used subtraction as an example

                      – wilada
                      Mar 22 at 19:20





                      Is there a way to do this with other more complicated functions? I just used subtraction as an example

                      – wilada
                      Mar 22 at 19:20













                      sure there is but without specifics I really can't answer or clarify

                      – aws_apprentice
                      Mar 22 at 19:20





                      sure there is but without specifics I really can't answer or clarify

                      – aws_apprentice
                      Mar 22 at 19:20













                      3














                      The following solution should work using a list comprehension:



                      result = []
                      for value1 in array1:
                      result.append([value1 - value2 for value2 in array2])


                      You could even write this in 1 line using both for loops for the list comprehension:



                      result = [[value1 - value2 for value2 in array2] for value1 in array1]





                      share|improve this answer



























                        3














                        The following solution should work using a list comprehension:



                        result = []
                        for value1 in array1:
                        result.append([value1 - value2 for value2 in array2])


                        You could even write this in 1 line using both for loops for the list comprehension:



                        result = [[value1 - value2 for value2 in array2] for value1 in array1]





                        share|improve this answer

























                          3












                          3








                          3







                          The following solution should work using a list comprehension:



                          result = []
                          for value1 in array1:
                          result.append([value1 - value2 for value2 in array2])


                          You could even write this in 1 line using both for loops for the list comprehension:



                          result = [[value1 - value2 for value2 in array2] for value1 in array1]





                          share|improve this answer













                          The following solution should work using a list comprehension:



                          result = []
                          for value1 in array1:
                          result.append([value1 - value2 for value2 in array2])


                          You could even write this in 1 line using both for loops for the list comprehension:



                          result = [[value1 - value2 for value2 in array2] for value1 in array1]






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 22 at 19:19









                          RemyRemy

                          1329




                          1329





















                              2














                              Loops solution:



                              array1 = [6, 7, 8]
                              array2 = [1, 2, 3, 4, 5]

                              arr = []
                              for i in array1:
                              tmp = []
                              for j in array2:
                              tmp.append(i - j)
                              arr.append(tmp)

                              print(arr)


                              Output:




                              [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]







                              share|improve this answer



























                                2














                                Loops solution:



                                array1 = [6, 7, 8]
                                array2 = [1, 2, 3, 4, 5]

                                arr = []
                                for i in array1:
                                tmp = []
                                for j in array2:
                                tmp.append(i - j)
                                arr.append(tmp)

                                print(arr)


                                Output:




                                [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]







                                share|improve this answer

























                                  2












                                  2








                                  2







                                  Loops solution:



                                  array1 = [6, 7, 8]
                                  array2 = [1, 2, 3, 4, 5]

                                  arr = []
                                  for i in array1:
                                  tmp = []
                                  for j in array2:
                                  tmp.append(i - j)
                                  arr.append(tmp)

                                  print(arr)


                                  Output:




                                  [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]







                                  share|improve this answer













                                  Loops solution:



                                  array1 = [6, 7, 8]
                                  array2 = [1, 2, 3, 4, 5]

                                  arr = []
                                  for i in array1:
                                  tmp = []
                                  for j in array2:
                                  tmp.append(i - j)
                                  arr.append(tmp)

                                  print(arr)


                                  Output:




                                  [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]








                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Mar 22 at 19:14









                                  ingvaringvar

                                  2,0671718




                                  2,0671718





















                                      2














                                      Your for loop is nearly correct except, you overwrite the value of ar every iteration (and you make it slightly more complicated with range)



                                      You can achieve this through list comprehension



                                      [[i - j for j in array2] for i in array1]
                                      # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]





                                      share|improve this answer



























                                        2














                                        Your for loop is nearly correct except, you overwrite the value of ar every iteration (and you make it slightly more complicated with range)



                                        You can achieve this through list comprehension



                                        [[i - j for j in array2] for i in array1]
                                        # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]





                                        share|improve this answer

























                                          2












                                          2








                                          2







                                          Your for loop is nearly correct except, you overwrite the value of ar every iteration (and you make it slightly more complicated with range)



                                          You can achieve this through list comprehension



                                          [[i - j for j in array2] for i in array1]
                                          # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]





                                          share|improve this answer













                                          Your for loop is nearly correct except, you overwrite the value of ar every iteration (and you make it slightly more complicated with range)



                                          You can achieve this through list comprehension



                                          [[i - j for j in array2] for i in array1]
                                          # [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3]]






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Mar 22 at 19:18









                                          SayseSayse

                                          29.9k115298




                                          29.9k115298





















                                              1














                                              You were on the right track but you had your arrays switched. You want array1 inside the inner loop to perform the operation you want to perform:



                                              array1 = [6,7,8]
                                              array2 = [1,2,3,4,5]
                                              finalarray=[]

                                              for i in range(len(array2)):
                                              for j in range(len(array1)):
                                              ar = array1[j]-array2[i]
                                              finalarray.append(ar)

                                              print(finalarray)

                                              >>>[5, 6, 7, 4, 5, 6, 3, 4, 5, 2, 3, 4, 1, 2, 3]





                                              share|improve this answer



























                                                1














                                                You were on the right track but you had your arrays switched. You want array1 inside the inner loop to perform the operation you want to perform:



                                                array1 = [6,7,8]
                                                array2 = [1,2,3,4,5]
                                                finalarray=[]

                                                for i in range(len(array2)):
                                                for j in range(len(array1)):
                                                ar = array1[j]-array2[i]
                                                finalarray.append(ar)

                                                print(finalarray)

                                                >>>[5, 6, 7, 4, 5, 6, 3, 4, 5, 2, 3, 4, 1, 2, 3]





                                                share|improve this answer

























                                                  1












                                                  1








                                                  1







                                                  You were on the right track but you had your arrays switched. You want array1 inside the inner loop to perform the operation you want to perform:



                                                  array1 = [6,7,8]
                                                  array2 = [1,2,3,4,5]
                                                  finalarray=[]

                                                  for i in range(len(array2)):
                                                  for j in range(len(array1)):
                                                  ar = array1[j]-array2[i]
                                                  finalarray.append(ar)

                                                  print(finalarray)

                                                  >>>[5, 6, 7, 4, 5, 6, 3, 4, 5, 2, 3, 4, 1, 2, 3]





                                                  share|improve this answer













                                                  You were on the right track but you had your arrays switched. You want array1 inside the inner loop to perform the operation you want to perform:



                                                  array1 = [6,7,8]
                                                  array2 = [1,2,3,4,5]
                                                  finalarray=[]

                                                  for i in range(len(array2)):
                                                  for j in range(len(array1)):
                                                  ar = array1[j]-array2[i]
                                                  finalarray.append(ar)

                                                  print(finalarray)

                                                  >>>[5, 6, 7, 4, 5, 6, 3, 4, 5, 2, 3, 4, 1, 2, 3]






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Mar 22 at 19:16









                                                  JeremiahJeremiah

                                                  687211




                                                  687211





















                                                      1














                                                      ar is not being treated properly in your code, it needs to be an array of arrays (matrix) and you'll need another variable to hold the result per iteration, there's probably a better way to do this using list comprehensions but here is one way:



                                                      array1 = [6,7,8]
                                                      array2 = [1,2,3,4,5]

                                                      ar = []
                                                      row = []
                                                      for i in range(len(array1)):
                                                      for j in range(len(array2)):
                                                      row.append(array1[i]-array2[j])
                                                      ar.append(row)
                                                      row = []
                                                      print ar





                                                      share|improve this answer



























                                                        1














                                                        ar is not being treated properly in your code, it needs to be an array of arrays (matrix) and you'll need another variable to hold the result per iteration, there's probably a better way to do this using list comprehensions but here is one way:



                                                        array1 = [6,7,8]
                                                        array2 = [1,2,3,4,5]

                                                        ar = []
                                                        row = []
                                                        for i in range(len(array1)):
                                                        for j in range(len(array2)):
                                                        row.append(array1[i]-array2[j])
                                                        ar.append(row)
                                                        row = []
                                                        print ar





                                                        share|improve this answer

























                                                          1












                                                          1








                                                          1







                                                          ar is not being treated properly in your code, it needs to be an array of arrays (matrix) and you'll need another variable to hold the result per iteration, there's probably a better way to do this using list comprehensions but here is one way:



                                                          array1 = [6,7,8]
                                                          array2 = [1,2,3,4,5]

                                                          ar = []
                                                          row = []
                                                          for i in range(len(array1)):
                                                          for j in range(len(array2)):
                                                          row.append(array1[i]-array2[j])
                                                          ar.append(row)
                                                          row = []
                                                          print ar





                                                          share|improve this answer













                                                          ar is not being treated properly in your code, it needs to be an array of arrays (matrix) and you'll need another variable to hold the result per iteration, there's probably a better way to do this using list comprehensions but here is one way:



                                                          array1 = [6,7,8]
                                                          array2 = [1,2,3,4,5]

                                                          ar = []
                                                          row = []
                                                          for i in range(len(array1)):
                                                          for j in range(len(array2)):
                                                          row.append(array1[i]-array2[j])
                                                          ar.append(row)
                                                          row = []
                                                          print ar






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Mar 22 at 19:20









                                                          bigwillydosbigwillydos

                                                          546310




                                                          546310





















                                                              1














                                                              There are plenty of good answers here, but another option especially useful for larger arrays is to use numpy, a package designed for moving large arrays of numbers efficiently. One possible answer in numpy would be this:



                                                              import numpy as np

                                                              array1 = np.arange(6,9) # make arrays 1 and 2
                                                              array2 = np.arange(1,6)
                                                              output = (array1.repeat(array2.shape[0]) # repeat array1 as many times as there are elements in array2
                                                              .reshape(array1.shape[0], -1) # reshape so we have a row for each element in array1
                                                              ) - array2 # subtract array2 from each row
                                                              output


                                                              array([[5, 4, 3, 2, 1],
                                                              [6, 5, 4, 3, 2],
                                                              [7, 6, 5, 4, 3]])





                                                              share|improve this answer



























                                                                1














                                                                There are plenty of good answers here, but another option especially useful for larger arrays is to use numpy, a package designed for moving large arrays of numbers efficiently. One possible answer in numpy would be this:



                                                                import numpy as np

                                                                array1 = np.arange(6,9) # make arrays 1 and 2
                                                                array2 = np.arange(1,6)
                                                                output = (array1.repeat(array2.shape[0]) # repeat array1 as many times as there are elements in array2
                                                                .reshape(array1.shape[0], -1) # reshape so we have a row for each element in array1
                                                                ) - array2 # subtract array2 from each row
                                                                output


                                                                array([[5, 4, 3, 2, 1],
                                                                [6, 5, 4, 3, 2],
                                                                [7, 6, 5, 4, 3]])





                                                                share|improve this answer

























                                                                  1












                                                                  1








                                                                  1







                                                                  There are plenty of good answers here, but another option especially useful for larger arrays is to use numpy, a package designed for moving large arrays of numbers efficiently. One possible answer in numpy would be this:



                                                                  import numpy as np

                                                                  array1 = np.arange(6,9) # make arrays 1 and 2
                                                                  array2 = np.arange(1,6)
                                                                  output = (array1.repeat(array2.shape[0]) # repeat array1 as many times as there are elements in array2
                                                                  .reshape(array1.shape[0], -1) # reshape so we have a row for each element in array1
                                                                  ) - array2 # subtract array2 from each row
                                                                  output


                                                                  array([[5, 4, 3, 2, 1],
                                                                  [6, 5, 4, 3, 2],
                                                                  [7, 6, 5, 4, 3]])





                                                                  share|improve this answer













                                                                  There are plenty of good answers here, but another option especially useful for larger arrays is to use numpy, a package designed for moving large arrays of numbers efficiently. One possible answer in numpy would be this:



                                                                  import numpy as np

                                                                  array1 = np.arange(6,9) # make arrays 1 and 2
                                                                  array2 = np.arange(1,6)
                                                                  output = (array1.repeat(array2.shape[0]) # repeat array1 as many times as there are elements in array2
                                                                  .reshape(array1.shape[0], -1) # reshape so we have a row for each element in array1
                                                                  ) - array2 # subtract array2 from each row
                                                                  output


                                                                  array([[5, 4, 3, 2, 1],
                                                                  [6, 5, 4, 3, 2],
                                                                  [7, 6, 5, 4, 3]])






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Mar 22 at 19:33









                                                                  coradekcoradek

                                                                  1149




                                                                  1149



























                                                                      draft saved

                                                                      draft discarded
















































                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                      But avoid


                                                                      • Asking for help, clarification, or responding to other answers.

                                                                      • Making statements based on opinion; back them up with references or personal experience.

                                                                      To learn more, see our tips on writing great answers.




                                                                      draft saved


                                                                      draft discarded














                                                                      StackExchange.ready(
                                                                      function ()
                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306357%2ffunctions-on-arrays-of-different-sizes-in-for-loop%23new-answer', 'question_page');

                                                                      );

                                                                      Post as a guest















                                                                      Required, but never shown





















































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown

































                                                                      Required, but never shown














                                                                      Required, but never shown












                                                                      Required, but never shown







                                                                      Required, but never shown







                                                                      Popular posts from this blog

                                                                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript