2

I am new to python and am struggling to figure out how to initialize an array of unicode chars to a certain size. I want to use arrays not lists as I desire O(1) random access and O(1) amortized cost for insertion. So far I have this:

from arrays import *
a = array('u')

but obviously this is a zero length array.

Thanks, Aly

3
  • 2
    Lists offer O(1) random access and armotized O(1) append (see the Python wiki). Arrays don't offer anything over that (they only shave off constant factors), and may even be worse for appending. Both arrays and lists require copying elements when inserting (adding a new item, not overwriting an existing one) in the middle of the sequence. I'm not aware of any data structure that offers worst-case O(1) access (has tables are armotized O(1)) and armotized O(1) insertion everywhere. Please clarify. Commented Dec 4, 2011 at 16:14
  • it always wondered me, why python does not have a standard way of doing this, same for normal lists. I usually go with [None]*100 or similar. Commented Dec 4, 2011 at 16:17
  • @delnan I dont mind using lists tbh given that I have now been made aware that they are just like Java ArrayLists, I am implementing a gap buffer so doubling the list and doing coppies myself is useful rather than just appending. Commented Dec 4, 2011 at 16:26

1 Answer 1

3

This creates a new array initialized to "unicode string".

from array import *
a = array('u', u"unicode string")

If you only want it initialized to a certain size, you can do this:

a = array('u', u'\0' * size)

This will initialize a unicode character array with size size initialized to null characters.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the first thing i thought of too, but I still find it to be quite uneasy on the eyes. You need to allocate the length of the array of dummy values for them to be copied. While this is a constant factor, it is still unnecessary.
array.array('u', (u'\0' for _ in xrange(100))) via a generator expression works too, but I still have the feeling, that the module internally is just doing an append operation for every item.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.