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
asked Dec 4, 2011 at 16:10
Aly
16.3k47 gold badges124 silver badges195 bronze badges
-
2Lists 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.user395760– user3957602011年12月04日 16:14:50 +00:00Commented 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.sleeplessnerd– sleeplessnerd2011年12月04日 16:17:33 +00:00Commented 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.Aly– Aly2011年12月04日 16:26:28 +00:00Commented Dec 4, 2011 at 16:26
1 Answer 1
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.
answered Dec 4, 2011 at 16:20
Håvard
10.1k1 gold badge43 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
sleeplessnerd
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.
sleeplessnerd
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.
lang-py