Tudor Hofnar Tudor Hofnar - 1 month ago 6
Python Question

How to insert elements into array without using append, Python?

I'm a beginner with Python and am having a bit of trouble inserting elements into an array without using the append() function.

This is part of my code which I hope illustrates enough but feel free to ask for more details if it helps:

#other code
arr1 = []
arr2 = []
index1 = 0
index2 = 0

for i in range(0, len(A)):
if A[i] < A[r]:
arr1[index1] = A[i]
index1 = index1 + 1
elif A[i] > A[r]:
arr2[index2] = A[i]
index2 = index2 + 1
#other code


A is declared above this code and the number of elements in it vary based on an input file for the program. Currently I'm getting the index out of range error and on the assignment of A[i] to arr1[index1]. Any ideas? I just can't seem to get this working in Python.

Thanks!

Answer

use + or +=:

>>> lis = []
>>> lis = lis + [1]
>>> lis
[1]
>>> lis = lis + [2]
>>> lis
[1, 2]
>>> lis += [3]  # += acts like list.extend, i.e changes the list in-place
>>> lis
[1, 2, 3]

The problem with your code is that the lists arr1 and arr2 are empty, so assigning values to indexes which don't exist yet is going to raise IndexError.

for i in range(0, len(A)):
    if A[i] < A[r]:
        arr1 = arr1  + [A[i]]

    elif A[i] > A[r]:
        arr2 = arr2 + [A[i]]
Comments