8

how can one sort an integer array (not a list) in-place in Python 2.6? Is there a suitable function in one of the standard libraries?

In other words, I'm looking for a function that would do something like this:

>>> a = array.array('i', [1, 3, 2])
>>> some_function(a)
>>> a
array('i', [1, 2, 3])

Thanks in advance!

3
  • Why have you ruled out using a list? Did you profile and find it lacking? If you must use an array and need it sorted, I suggest using numpy, which has a sort method for arrays. Commented Apr 4, 2011 at 14:51
  • 2
    @Steven Yes, I have profiled it. I'm working on large collections of integers that barely fit in RAM. Lists of integers are at least 3 times larger than arrays of integers, so I cannot use them. Could you (or anyone else) point to a relevant function in SciPy/NumPy? Commented Apr 4, 2011 at 14:59
  • 1
    Start at docs.scipy.org/doc/numpy/reference/routines.sort.html. Note that the default sort returns a copy, but ndarray.sort sorts in-place. (I have no experience with SciPy/NumPy, but do know that it is well respected and highly optimized.) Commented Apr 4, 2011 at 15:03

3 Answers 3

10

Well, you can't do it with array.array, but you can with numpy.array:

In [3]: a = numpy.array([0,1,3,2], dtype=numpy.int)

In [4]: a.sort()

In [5]: a
Out[5]: array([0, 1, 2, 3])

Or you can convert directly from an array.array if you have that already:

a = array.array('i', [1, 3, 2])
a = numpy.array(a)
Sign up to request clarification or add additional context in comments.

1 Comment

And this appears to be an in-place sort. Good answer.
2

@steven mentioned numpy.

Copies vs. in-place operation
-----------------------------
Most of the functions in `numpy` return a copy of the array argument
(e.g., `sort`).  In-place versions of these functions are often
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
Exceptions to this rule are documented.

Comments

1

Looking at the array docs, I don't see a method for sorting. I think the following is about as close as you can get using standard functions, although it is really clobbering the old object with a new one with the same name:

import array
a = array.array('i', [1,3,2])
a = array.array('i', sorted(a))

Or, you could write your own.

With the extra information from the comments that you're maxing out memory, this seems inapplicable for your situation; the numpy solution is the way to go. However, I'll leave this up for reference.

Comments

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.