6

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!

4
  • What is r supposed to be? Commented Jun 16, 2013 at 20:06
  • 3
    What's the reason for not using .append? Commented Jun 16, 2013 at 20:07
  • r is the last element of my input array. sorry, I forgot to mention that, basically the same value as len(A) Commented Jun 16, 2013 at 20:14
  • len(A) is the length of the list. The last element is at the index len(A) - 1, you can also use negative number, then it would be A[-1]. Commented Jun 16, 2013 at 20:55

2 Answers 2

9

You can do that using + or += operators:

>>> 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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton! That works, I used + instead of +=, any one of them more efficient than the other, or better to use in this situation?
@TudorHofnar += changes the list in-place, on the other hand + creates a new list everytime. Prefer += over +. A related post : stackoverflow.com/questions/15376509/…
2

It looks like you are trying to implement something similar to quicksort. Lists in python are in reality growing arrays. New list is empty, so you can't insert a value into it by using an index. Using append is the best option here, e.g.:

a = [1, 5, 3, 2, 6, 7]
al = []
ag = []
for x in a:
    if x < 4:
        al.append(x)
    else:
        ag.append(x)

Now al == [1, 3, 2] and ag == [5, 6, 7].

If you already have an existing list, then you can access its elements by using an index. Another example where I have created the lists beforehand:

a = [1, 5, 3, 2, 6, 7]
al = 3 * [0]
ag = 3 * [0]
index_l = 0
index_r = 0
for i in range(len(a)):
    if a[i] < 4:
        al[index_l] = a[i]
        index_l += 1
    else:
        ag[index_r] = a[i]
        index_r += 1

I don't think this is very pythonic, and you have to know how large you lists must be. Please don't use this approach.

Also, it's not a good idea to use al += [a[i]], it's doing the same as append, but you are creating intermediate lists, so it's slower:

>>> timeit.timeit('a += [1]', 'a = [1,2,3]')
0.14568603380625794
>>> timeit.timeit('a.append(1)', 'a = [1,2,3]')
0.07830060367457214

Example of a simple quicksort:

def qsort(data):
    if len(data) <= 1:
       return data
    pivot = data[0]
    smaller = []
    greater = []
    for x in data[1:]:
        if x < pivot:
            smaller.append(x)
        else:
            greater.append(x)
    return qsort(smaller) + [pivot] + qsort(greater)

3 Comments

Yep, I was implementing quicksort, but I can't use append or any built in functions so that is why I was looking for an alternative such as +=, unfortunately :(. BTW thanks for the reply, helped me understand things better :)
Well, what exactly does it mean that you can't use any built in functions? += is also a built in function, sort of. Maybe you should implement an in-place version? en.wikipedia.org/wiki/Quicksort#In-place_version
@DavidMarek your solution is using the append method, but Tudor requested a solution without it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.