Search code examples
pythonarrayspython-2.7for-looparray-merge

Merging two arrays using 'for loop'


I want to merge two arrays in python 2.7 using 'for loop' given:


from array import *
ary_1 = array ('i',[11,12,13])
ary_2 = array ('i',[14,15,16])
ary_3 = array ('i')

should give the output on ary_3 ,so ary_3 will display like this in specific order:


ary_3 = array ('i',[11,12,13,14,15,16])

Here's my code so far:


from array import *
ary_1 = array ('i',[11,12,13])
ary_2 = array ('i',[14,15,16])
ary_3 = array ('i')
ary_len = len (ary_1) + len (ary_2)
for i in range (0,ary_len):
    ary_3.append (ary_1 [i])
    ary_3.append (ary_2 [i])
    if len (ary_3) == len (ary_1) + len (ary_2):
       print ary_3,
       break

Then the output was:


array('i',[11,14,12,15,13,16])

Not in order actually, and also if I add a new integer on either ary_1 or ary_2, it gives "index out of range" error so I found out that ary_1 and ary_2 should have an equal amount of integer/s to prevent this error.


Solution

  • If you want to combine the arrays, you can use the built-in method .extend:

    ary_1.extend(ary_2)
    print ary_1 #array('i', [11, 12, 13, 14, 15, 16])
    

    As SethMMorton points out in the comments, if you do not want to override your first array:

    ary_3 = ary_1 + ary_2
    print ary_3 #array('i', [11, 12, 13, 14, 15, 16])
    

    You should use one of the approaches above, but for learning purposes in your original for loop you are (incorrectly) interleaving the two arrays by doing

    ary_3.append (ary_1 [i])
    ary_3.append (ary_2 [i])
    

    If you wanted to keep the for loop, it should look something like:

    ary_1_len = len(ary_1)
    for i in range (0,ary_len):
        if i < ary_1_len:
           ary_3.append (ary_1 [i])
        else:
           ary_3.append (ary_2 [i-ary_1_len])
        if len (ary_3) == len (ary_1) + len (ary_2):
           print ary_3
           break
    

    Such that you populate the third array with the first array, and then the second array.