Python speed question

A quick speed question, I was reading about arrays and as far as i could see one way to make them is nested lists, i.e. [[item1, item2][item3,item4].
However if you know the size of each list speed wise are you better off storing all items in one large list [item1, item2, item3, item4] and then getting items i and i+1to get your two items you would usually take as one list.
Thanks in advance, it’s just a curiosity thing, if it is faster what sort of speed gains would you get. I know it probably depends on list sizes.


these kind of questions are terribly hard to answer because so many factors play a role. The best thing to ask first is: is it already fast enough? Otherwise don’t bother :slight_smile:
However if you truly need the speed increase, the simplest approach is to implement your core code in two ways and time the difference. (python provides a module to time pieces of code ).

Having said that, there are some general answers to your question: Doing the list artihmatic yourself instead of letting python do its thing is probably not gonna help: the overhead involved in the doing that at the python level instead of letting python do it at a lower level, is too large. If you have a very large array with relatively few entries that you want to access (a so called sparse array) you might want to implement an array as a dictionary where you access items by giving a tuple as key:

v = dictarray[(x,y)] # you can leave out the () if you wish as x,y == (x,y)

Python also has a real array type (lists that can hold only items of the same type, e.g. only floats) that might be much faster than pythons lists. (see )

Finally, their exist special purpose libraries to address operations on arrays. Numpy is an example, that provide very fast implementations.


Thanks, thats all really usefull and interesting information there.

Tested float array Vs. python list through xrange() in Blender 2.49b.
Simple iteration through already created array gives almost the same speed as python list. However, array.append() method is slower than that of python list. Python list.append() method is about 165% faster on my machine.