1

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.

Bob Reas
  • 13
  • 1
  • 5
  • 1
    In Python, there is a lot of focus on [duck typing](https://stackoverflow.com/questions/4205130/what-is-duck-typing), one effect of this being that all sequences behave roughly the same no matter the specific type. Since `list` and `tuple` (both sequences) support `a + b`, you should first assume that `array` also supports that before trying to do something more complicated. – SethMMorton Jul 22 '17 at 01:44
  • Arrays are iterable, so if you _must_ use `for` loops, two would be far simpler than one: `for item in ary_1: ary_3.append(item)` then `for item in ary_2: ary_3.append(item)`. No counters, no indexing, no out-of-range errors. (You should still just use the built-in `+` operator, though.) – Kevin J. Chase Jul 22 '17 at 02:09

1 Answers1

5

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.

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
  • 1
    Or even `ary_3 = ary_1 + ary_2`, since it seems the OP wants a 3rd array and does not seem to want to overwrite `ary_1`. – SethMMorton Jul 22 '17 at 01:40