4 ms·
Getting the length of a string is a bad idea. Usually you do this because you want to iterate over the string one character at a time. But getting the character
by oofabz 14y ago
Getting the length of a string is a bad idea. Usually you do this because you want to iterate over the string one character at a time. But getting the character at a particular index is an O(n) operation, so iterating over a string this way is O(n^2).
This is 2013, strings are Unicode now, and we have to stop thinking of them as arrays of characters. The most widely used Unicode encodings, UTF-8 and UTF-16, both have variable-length characters.
- MichaelSalib 14y agoThe most obvious way to iterate over a string character by character in Python is 'for char in string: ...'; that loop invokes str.__iter__ which will be an O(n) rather than O(n^2) operation.
- bskap 14y agoAs of Python 3.3, unicode string indexing in Python is a constant time operation. http://www.python.org/dev/peps/pep-0393/ http://www.python.org/dev/peps/pep-0393/
- dalke 14y agoUnicode string indexing has always been constant time. On UCS-2 builds, the index might have returned the wrong thing, compared to what a UCS-4 build would have returned.