0

I have two array in python, name is data2004 and data2011. I want to append data in 2004 to 2011. but I get error like this IndexError: index 66 is out of bounds for axis 0 with size 66. my array like this

adddata = []
data2004 = [2,3,4,5]
data2011 = [6,7,8,9,10]
for d2 in range(0, len(data2011[d2])):
    adddata.append(list([data2004[d2], data2011[d2]])

I know data2004 just have 4 data and data2011 have 5 data, but I when if data2004 in last array change to 0. and the the result like this

adddata = [[2,6], [3,7], [4,8], [5, 9], [0, 10]]

please help me, thank you

Zmx Atah
  • 85
  • 1
  • 7

2 Answers2

1

Check if the index is in range of data2004, and use 0 if it isn't.

for d2 in range(0, len(data2011)):
    for r2 in range(0, len(data2011[d2])):
        if d2 < len(data2004):
            adddata.append([data2004[d2][r2], data2011[d2][r2]])
        else:
            adddata.append([0, data2011[d2][r2]])
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can try this too:

 adddata = [list(e) for e in list(itertools.zip_longest(data2004, data2011, fillvalue = 0 ))]
imraklr
  • 218
  • 3
  • 11